我是 React 上下文的新手,但我认为 redux 的工作原理是这样的,但没有找到正确的方法。
所以我有一个组件,一旦我获得数据,我将从 api 获取数据,一旦数据加载组件,我需要显示加载器
但是我如何将值设置为上下文并使用它。
看下面的片段
class App extends Component{
componentDidMount(){
this._fetchData()
}
_fetchData = async () => {
const response = await fetch("http://www.example.com", {method: "GET"})
const data = await response.json()
// how can i use context and set the value
}
// how should i use a provider to the router so basically i need to get the data every where in the route
render(){
return(
<Router>
{ Object.keys(context.data).length > 0 ?
<Layout>
<Switch>
<Route path="/sample" exact component={SampleHomePage} />
<Route path="/sample/profile" component={SampleProfile} />
<Route path="/sample/about" component={SampleAbout}/>
</Switch>
</Layout>
: <p>Data Loading </p>}
</Router>
)
}
}
// profile.js
import React from 'react';
const profile = () => {
//how to get the contex value here
}
export default profile
最佳答案
看看这个 codesandbox 并检查我是如何处理上下文的。
https://codesandbox.io/s/2p0koqr81p
关键是您需要一个额外的组件作为上下文。 在这种情况下,我只是将提取调用中的数据保存到上下文中。
因此,您必须向上下文提供更新的数据,然后您才能在任何您想要的组件中使用它。
我同意@Joru 的观点,在您的用例中使用上下文可能是不必要的,但我正在尝试回答这个问题。
关于javascript - 将上下文与 api 调用一起用于根级组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147539/