首页 > 解决方案 > 将父道具异步更新到子组件

问题描述

如何在异步操作后将更新的父组件的 props 发送到子组件。有没有可用的生命周期方法

 class SignUp extends Component {
  constructor(props){
    super(props);
    this.state = {...props};
  }

  componentDidMount(){
   this.props.UserSignupType();
  }
  render(){
    <Inputs {...this.state} >
  }
}

const stateToProps = state => ({
  signupInputs: state.signupInputs
});

connect(stateToProps, null)(SignUp);

class Inputs extends Component {
  constructor(props){
    super(props);
    this.state = {...props};
  }
  render(){
    if(!this.state.isLoaded) {
      return <Loading />
    } else {
      let inputs = [];
      this.state.inputs.forEach(function(input){
        inputs.push(<TextField value={input.text}>)
      });
      return <View>{inputs}</View>
    }
  }
}

注意:异步更新后传递道具可能重复给子组件

标签: reactjsreact-native

解决方案


第一次更正:如果您不更新它,则不需要从道具中添加状态数据。此外,如果您正在更新它,它应该处于子组件的状态。所以父组件可以像这样直接将 props 传递给子组件:

<Inputs {...this.props} >

现在在Inputs组件中,props如果它不会更改,您可以直接使用,或者您可以使用componentWillReceiveProps函数将其添加到状态,如下所示:

componentWillReceiveProps(nextProps){
   this.setState({...nextProps});
}

推荐阅读