在父组件的状态更改中重新呈现子组件

问题描述 投票:0回答:3

我正在使用react-navigation在两个屏幕之间导航,同时在它们之间传递数据。

流程:屏幕A(传递数据) - >屏幕B - >(更新并传回数据)屏幕A.

在屏幕A中,我正在使用一个子组件,它需要在从屏幕B接收数据时进行更新/重新渲染。

我已经检查了数据是否正确传递,并且我肯定正在更新主屏幕中子组件使用的状态。我只是无法弄清楚为什么子组件在读取新的状态值后没有重新渲染?

主屏幕:

updateCount(data) {
    // Logic to update state of a counter variable
    this.setState({ count: data })
}

// and then later on in the code, I'm calling the child Component 'B'        
<B prop={this.state.count} />

组件B:

componentWillMount() {
// based on value of this.props.count, I'm setting the value of 'text' in this component
    if(this.props.count == 1) {
       this.setState({text: 'abc'})
    } else {
       this.setState({text: 'cde'})
    }
}

// later on in the code, render method:
<View>
   <Text>
     {this.state.text}
   </Text>
</View>
reactjs react-native react-navigation
3个回答
0
投票

更新组件B :(以下代码)

    constructor(props) {
            super(props);
            this.state = {
                count: props.count
            };
         }

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

       componentDidMount() {
             this.setTextValue();
       }

         componentWillUpdate() {
             this.setTextValue();
       }

         setTextValue = () => {
           if(this.state.count == 1) {
               this.setState({text: 'abc'})
           } else {
              this.setState({text: 'cde'})
            }
         }

包括其余代码。

研究很好地反应lifecycle methods


0
投票

回答我的问题是因为我意识到我没有更新组件代码中的prop值以反映父元素状态的变化。

我想这就是为什么我在第一时间如此困惑,因为重新渲染国家的变化是React工作的核心。我使用react-devtools来调试并计算出我的Child组件的生命周期。现在一切正常!不知道我是否需要钩子/其他生命周期方法来实现这个简单的功能,但我感谢大家的帮助!


-1
投票

您必须使用componentDidUpdate。但是,如果使用钩子,那将会淘汰componentDidMount和componentDidUpdate。对于基于类的示例,它可能与此类似。

    componentdidUpdate(prevProps, props) => {
      if(prevProps.count !== this.props.count){
    if(this.props.count == 1) {
      this.setState({text: 'abc'})
       }
        else {
     this.setState({text: 'cde'})
      }}

但是,根据文档,这些方法被认为是遗留的,您应该在新代码中避免使用它们:

UNSAFE_componentWillMount()

删除它有利于componentDidMount和componentDidUpdate,或切换到钩子(这是最好的选择!)

© www.soinside.com 2019 - 2024. All rights reserved.