我正在尝试在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>
</>
)
}
}
答案 0 :(得分:0)
您需要做的就是保持加载状态,并在数据可用后呈现提供者
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>
</>
)
}
}