创建具有生命周期方法和最佳可能方式的上下文提供程序

问题描述 投票:0回答:1

我正在尝试在react应用程序中创建一个上下文提供程序,它可以在第一次实际呈现之前利用生命周期方法进行数据检索。我也希望更好地使组件的结构。有没有人有任何建议?

import React from 'react'

let defaultValue = {
    state: {
        accountID: 4885,

    },
}

export const Data = React.createContext(defaultValue)

interface State {
    getFeatureData: any
}

// Provider Component
export default class DataProvider extends React.Component<null, State> {
    state = defaultValue.state

    componentDidMount() {
        // something here?

    }

    render() {
        return (
            <>
                <Data.Provider
                    value={{
                        state: this.state
                    }}
                >
                    {this.props.children}
                </Data.Provider>
            </>
        )
    }
}
reactjs gatsby
1个回答
0
投票

您需要做的就是维护加载状态,并在数据可用后呈现Provider

import React from 'react'

let defaultValue = {
    state: {
        accountID: 4885,
        loading: true

    },
}

export const Data = React.createContext(defaultValue)

interface State {
    getFeatureData: any,
    loading: boolean
}

// Provider Component
export default class DataProvider extends React.Component<null, State> {
    state = defaultValue.state

    componentDidMount() {
        // something here?
        APICall().then(() => {
          this.setState({ loading: false });
        })

    }

    render() {
        const { loading, ...rest} = this.state;
        if (this.state.loading) {
          return <div>Loading...</div>; // or you can return an interactive loader here
        }
        return (
            <>
                <Data.Provider
                    value={{
                        state: rest
                    }}
                >
                    {this.props.children}
                </Data.Provider>
            </>
        )
    }
}

Working Demo

© www.soinside.com 2019 - 2024. All rights reserved.