我有两个组件。 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/