异步更新后将道具传递给子组件

时间:2018-06-19 15:05:36

标签: reactjs react-native

异步操作后更新的道具必须传递到输入组件。异步操作完成后如何将道具传递给子组件。

我正在尝试在Child组件中不连接。这可能吗

class SignUp extends Component {
  componentDidMount(){
   this.props.UserSignupType();
  }
  render(){
    <Inputs {...this.props} >
  }
}

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

在@Adam回答后更新:

注意:我已经尝试过this.state.isLoaded和this.props.isLoaded。两种方法都无法获取数据

更新2:

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

1 个答案:

答案 0 :(得分:2)

您在正确的轨道上。

您不需要将子组件连接到redux存储。您正在将道具传递给孩子,但问题是在孩子的构造函数中,您将这些道具置于状态,然后将其丢弃。因此,对父代道具的任何后续更改都不会不会传播给孩子。

在您的孩子中,您应该做if(!this.props.isLoaded)而不是if(!this.state.isLoaded)。这应该可以解决您的问题。

相关问题