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

React-Native: State is changed, but returning old value

我有两个组成部分。 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。 我将道具传递给 ComponentB 错了吗?我错过了什么吗?

提前致谢。

将您的 setState 移出视图;

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} />

您需要在 onPress

上传递状态

喜欢

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

组件 B

state = {
 filter: this.props.filter
}

componentWillReceiveProps(nextProps) {
 if(this.props.filter !== nextProps.filter){
   this.setState({
     filter: nextProps.filter
   })
 }
}

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

这可能会解决您的道具在父状态更改时不更新的问题。