异步将父道具更新为子组件

时间:2018-06-19 15:49:54

标签: reactjs react-native

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

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

注意:Pass props to child components after Async update

可能重复

3 个答案:

答案 0 :(得分:0)

可以通过getDerivedStateFromProps更新状态。 这是一种静态方法,您可以在其中比较状态和新道具并更新状态。

static getDerivedStateFromProps(nextProps, prevState) {
// Store myId in state.
if (nextProps.myId !== prevState.myId) {
  // this updates the state
  return {
    myId: nextProps.myId
  };
}

// This implies it won't update the state
return null;

}

答案 1 :(得分:0)

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

<Inputs {...this.props} >

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

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

答案 2 :(得分:0)

为什么需要将子组件的状态设置为收到的道具?我只是直接使用道具。

在您的情况下,我不确定刷新时会调用构造函数,因此子组件的状态不会更新。尝试直接使用道具。

相关问题