I'm playing with REACT context trying to update a login from a Child component to an App component when I press the button on the Child component.
Full code here.
因此,在同一文件中有两个组件:App和Child。
这是我的UserContext,带有login变量和用于更新登录名的函数(使用loginUpdated)
const UserContext = React.createContext({
login: 'defaultLogin',
updateLogin: (loginUpdated) => {}
});
在App组件中,我在Child组件周围有UserContext.Provider:
class App extends React.Component {
constructor(props) {
super(props);
this.appLoginUpdate = this.appLoginUpdate.bind(this);
this.state = {
login: "AppLoginValue"
}
}
appLoginUpdate(login) {
console.log("1. appLoginUpdate method => login value: ", login)
this.setState({
login: login
})
console.log("2. appLoginUpdateLogin method after state update :", this.state.login)
}
render() {
const contextValue = {
login: "contextValueLogin",
updateLogin: this.appLoginUpdate
}
return (
<UserContext.Provider value={contextValue}>
<Child />
</UserContext.Provider>
);
}
}
最后我得到了Child组件
class Child extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
static contextType = UserContext;
handleClick() {
this.context.updateLogin("ChildValueLogin")
}
render() {
console.log("3. Context login value : ", this.context.login)
return (
<div>
<h1>{this.context.login}</h1>
<button onClick={this.handleClick}>UPDATE LOGIN</button>
</div>
)
}
}
在单击“ UPDATE LOGIN”按钮之前,我已经在控制台中找到了它:
3. Context login value : contextValueLogin
[没关系,这是在App中赋予contextValue.login的值]
第一次单击“ UPDATE LOGIN”按钮时,我已经在控制台中找到了:
1. appLoginUpdate method => login value: ChildValueLogin
[可以,登录参数的期望值]
2. appLoginUpdateLogin method after state update : AppLoginValue
[不好,this.state尚未更新]
3. Context login value : contextValueLogin
[也很糟糕]
当我再次单击时:
1. appLoginUpdate method => login value: ChildValueLogin
[再次确定]
2. appLoginUpdateLogin method after state update : ChildValueLogin
[现在第二次单击就可以了吗? ]
3. Context login value : contextValueLogin
[糟糕,从未更新]
我希望您能帮助我找出此代码中的问题。谢谢你的帮助。
setState
updates state asynchronously. Change setState function to查看更改后的状态。
setState
function takes an optional callback function parameter which is called after state has been updated. If you want to see the changes in the state immediately after updating it, you need to put yourconsole.log
statement inside this callback function