从一个子节点更改parent's状态,并在另一个子节点react-native中使用它

Change parent's state from a child and use it in another child react-native

本文关键字:子节点 另一个 状态 react-native 一个 parent      更新时间:2023-09-26

我需要从子组件B更改父组件A的状态,并在父组件A的另一子组件C中使用更新后的状态。我做了以下的事情。我可以从子组件更新父组件,但第二个子组件仍然获得父组件的旧状态。那么这里有什么问题呢?

组件A有B、C子组件。(这里,A也是某人的孩子)

  class A extends Component {
        constructor(props) {
          super(props);
        });
        this.state = {
          name:this.props.name // first it gets name from A's parent
        }
        setName(UpdatedName){
          this.setState({ name: UpdatedName });    
        }
       render() {
          return (
            <View>
             <B callBackFromA={this.setName.bind(this)}/>
             <C name={this.state.name}/>
            </View>);
          }
       }

从A的子组件B中,我想从回调函数中更改A的state.name。它确实(经过测试)

 class B extends Component {
            constructor(props) {
              super(props);
              callBackFromA :this.props.callBackFromA
            });
            this.state = {                 
            }
         render() {
          return (
            <View>
             <TouchableOpacity onPress={()=>this.callBackFromA('new name')}> </TouchableOpacity>
            </View>);
          }
       }
    }

A的state.name也作为prop传递给A的另一个子组件C。在我从B中更改了A的state.name之后,我需要从组件c中保存它。

  class C extends Component {
            constructor(props) {
              super(props);
            });
            this.state = {
              name:this.props.name
            }
            saveData(){
              //..problem is that this getting old state.name of A after B changes..
              console.log(this.state.name);   
            }
         render() {
          return (
            <View>
             <TouchableOpacity onPress={()=>this.saveData()}> </TouchableOpacity>
            </View>);
          }
       }
    }

你需要在C类中使用componentWillReceiveProps函数。使用这个方法,你可以根据更新后的props来更新C类。

componentWillReceiveProps(nextProps)
{
   if(this.props.name != nextProps.name)
   {
    //do your task
     this.setState({name:nextProps.name})
   }
}
https://facebook.github.io/react/docs/component-specs.html

组件C不应该使用该状态。State只有在需要从组件内部更改信息时才有用,如果您只需要从上面的组件传递的信息,则只需指向props。

class C extends Component {
  saveData(){
    console.log(this.props.name);   
  }
  render() {
    return (
      <View>
        <TouchableOpacity onPress={() => this.saveData()}> </TouchableOpacity>
      </View>);
  }
}

如果你必须将属性转移到一个状态,那么请参考Burak的回答