gpt4 book ai didi

javascript - React-Native:状态已更改,但返回旧值

转载 作者:行者123 更新时间:2023-11-28 14:59:13 25 4
gpt4 key购买 nike

我有两个组件。 ComponentA 上有一个按钮,当你点击它时,它会改变状态:

import ComponentB from './ComponentB'
.
.
constructor(props) {
super(props);
this.state = {
filter: true,
};
}
.
.
.
<TouchableOpacity
onPress={()=>{ this.setState({filter: !this.state.filter }); }}
>
{this.state.filter ?
<Text>Enabled</Text> :
<Text>Disabled</Text>
}
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />

ComponentB

render(){
return(
<View><Text>{this.props.filter}</Text></View>
);
}

有趣的是,当您单击按钮时,状态确实会发生变化,并且基于状态的文本也会发生变化。所以第一次它从 True 变为 False。但 ComponentB 仍然会收到 True 而不是 False。当您再次点击它时,状态从 False 变为 True,文本也正确显示,但这次 ComponentB 将收到 True而不是 False。我将 props 传递给 ComponentB 是否错误?我错过了什么吗?

提前致谢。

最佳答案

将 setState 移出 View ;

import ComponentB from './ComponentB'
.
.
constructor(props) {
super(props);
this.state = {
filter: true,
};
}
changeFilter = () => { this.setState({filter: !this.state.filter }); };
.
.
.
<TouchableOpacity
onPress={()=> this.changeFilter(); }
>
{this.state.filter ?
<Text>Enabled</Text> :
<Text>Disabled</Text>
}
</TouchableOpacity>
.
.
.
<ComponentB filter={this.state.filter} />

关于javascript - React-Native:状态已更改,但返回旧值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41722030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com