React Context API - 获取更新的状态值
2020-03-28
1783
我正在尝试使用 React 上下文 API,
请检查
someComponent
函数,我在该函数中传递了点击事件(
updateName
函数),然后从
GlobalProvider
函数更新
state.name
值
更新
state.name
后,它将反映在浏览器中,但不会在控制台中获取更新的值(我已在点击函数行下方调用控制台以获取下方的更新值)
为什么在控制台中获取不到更新的值,但它在渲染内部(在浏览器上)?
示例代码
App function
<GlobalProvider>
<Router>
<ReactRouter />
</Router>
</GlobalProvider>
=== 2
class GlobalProvider extends React.Component {
state = {
name: "Batman"
};
render() {
return (
<globalContext.Provider
value={{
name: this.state.name,
clickme: () => { this.setState({ name: "Batman 2 " }) }
}}
>
{this.props.children}
</globalContext.Provider>
);
}
}
export default GlobalProvider;
=== 3
const SomeComponent = () => {
const globalValue = useContext(globalContext);
const updateName = ()=> {
globalValue.clickme();
console.log(globalValue.name ) //*** Here is my concern - not getting updated value here but , getting updated value in browser
}
return (
<div onClick={(e)=> updateName(e) }>
{globalValue.name}//*** In initial load display - Batman, after click it display Batman 2
</div>) }
1个回答
React 状态不是像 Vue 或 Angular 状态这样的观察者,这意味着你无法在更改它们之后立即获取更新的值。
如果你想在更改它们之后获取更新的值,你可以按照以下解决方案:
class A extends Component {
state = {
name: "Test"
}
updateName = () => {
this.setState({name: "Test 2"}, () => {
console.log(this.state.name) // here, name has been updated and will return Test 2
})
}
}
因此,你需要为 clickme 编写一个回调函数并按如下方式调用它:
class GlobalProvider extends React.Component {
state = {
name: "Batman"
};
render() {
return (
<globalContext.Provider
value={{
name: this.state.name,
clickme: (callback) => { this.setState({ name: "Batman 2 " }, () => callback(this.state.name)) }
}}
>
{this.props.children}
</globalContext.Provider>
);
}
}
export default GlobalProvider;
并使用:
const SomeComponent = () => {
const globalValue = useContext(globalContext);
const updateName = ()=> {
globalValue.clickme((name) => {
console.log(name) // Batman 2
});
}
return (
<div onClick={(e)=> updateName(e) }>
{globalValue.name}//*** In initial load display - Batman, after click it display Batman 2
</div>)
}
Ali Torki
2020-03-28