繁体   English   中英

从孩子更改父母的状态,并将其用于其他孩子

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

我需要从子组件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也作为道具传递给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函数。 使用此方法,您可以根据其更新的道具来更新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不应使用该状态。 仅当信息需要从组件内部更改时,状态才有用,如果您需要的只是从上面的组件传递的信息只是指向道具。

class C extends Component {

  saveData(){
    console.log(this.props.name);   
  }

  render() {
    return (
      <View>
        <TouchableOpacity onPress={() => this.saveData()}> </TouchableOpacity>
      </View>);
  }
}

如果必须将财产转移到州,请参阅Burak的答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM