首页 > 解决方案 > 异步更新后将 props 传递给子组件

问题描述

异步操作后更新的 props 必须传递给 Inputs 组件。异步操作完成后如何将 props 传递给子组件。

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

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

标签: reactjsreact-native

解决方案


你在正确的轨道上。

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

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


推荐阅读