我是React的新手,如果这是一个不好的问题,对不起。我在更改子组件的状态,然后调用更改父组件的状态的方法时遇到麻烦。现在,当我触发应该更改状态的方法时,父状态会按原样更改,但子状态根本不会更改。
当我删除“父”组件上的状态更改时,子组件也会发生应有的变化。
这是父组件(已编辑以删除与该问题无关的代码)
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
loginModalName: "Log in"
}
this.bindedUpdateModalName = this.updateModalName.bind(this)
}
updateModalName(name) {
console.log(name);
this.setState({
loginModalName: name
});
};
render() {
return (
<Child loginSwitch = {this.bindedUpdateModalName}/>
);
}
}
这是子组件
class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggingIn: true
}
}
toggleLoggingIn = () => {
this.setState({
isLoggingIn: !this.state.isLoggingIn
});
console.log(this.state.isLoggingIn);
this.props.loginSwitch(this.state.isLoggingIn ? "Log in" : "Register");
};
render() {
return (
<Button onClick={this.toggleLoggingIn} type="link" style={{paddingLeft: 0}}>register now!</Button>
);
}
没有错误消息,但是我的日志显示
true
Log In
每次我点击按钮
最佳答案
这是因为setState
是异步的。您需要等待状态更改发生(setState
或componentDidUpdate
的第二个回调选项),或者可以使用诸如isLogin
这样的变量来保存新的状态值。将您的处理程序更改为此
toggleLoggingIn = () => {
const isLogin = !this.state.isLoggingIn
this.setState({
isLoggingIn: isLogin
});
console.log(this.props.loginSwitch);
this.props.loginSwitch(isLogin ? "Log in" : "Register");
};
Check it out in action!
您遇到的问题是尝试在
antd
表单上使用本地状态。您应该使用父状态并作为道具传递,或使用antd
方法在HOC上更新“状态”关于reactjs - 调用父方法时,子setState不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56398938/