反应成分 - 亲子互动;组件生命周期

时间:2017-08-30 00:20:20

标签: reactjs react-native react-redux

我正在开发一个简单的浏览器应用程序来从用户那里获取一些特定数据。 我有几个组件来简化收集数据的过程,但我目前正在重新思考我渲染这个组件的方式。

基本上,我有我的主要组件,它使用state来跟踪要呈现的组件。

我正在为几乎所有组件执行此操作。 此外,我还在父组件中有一个函数,我通过props传递给子组件,并且当该组件不再有用时,它被用作回调以将子状态传递给它的父组件。

class Main extends React.Component {
  constructor(props){
     this.state = {
        renderA: true,
        renderB: false,
        childState: null
     }
  }

  collectState(state){
      this.setState({
         childState: state
     });
  }

  render() {
     let content = null;
     if(this.state.renderA === true){
         content = <ComponentA />
     } else {
         content = <ComponentB />
     }
     return(
      <div>
         {content}
      </div>);
   }
}

所以,使用上面的例子,孩子会是这样的

class ComponentA extends React.Component {
   constructor(props){
     super(props);
     this.state = {
        stop: false,
        usefullInfo: null
     }

   destroy() {
      this.props.collectstate(this.state.usefullInfo)
   }

   render(){
    render something (like a Form) untill this.state.usefullInfo is set;
    in that case, set this.state.stop true which will call destroy, passing the usefull information to parent
   }
}

所以,这种方法适合我,但我可以清楚地看到,这很可能不是这样做的方法。

此时我的问题是:

1)如何停止渲染组件而不必使用像this.state.stop这样的属性来跟踪它?

2)如果我想渲染2个不同的组件,比如在主组件中,我是否总是要将renderA和renderB属性保持在状态,以呈现一个或另一个?

3)有没有更好的方法将信息从孩子传递给父母?我目前正在使用通过道具从父到子传递的回调函数,我在组件完成其目的时调用该回调

4)关于如何提高上述代码质量的一般性建议?

谢谢你的帮助:)!

1 个答案:

答案 0 :(得分:1)

您的示例工作正常,但在React中,建议在处理来自多个子项(source)的数据时解除状态。因此,我建议保留父母中每个孩子的状态,并将带有价值观和处理程序的道具传递给孩子。

这是您可以查看的sample app。表单组件处理您要实现的案例。

回答你的问题:

  1. 父组件应根据自己的状态决定是否呈现子组件。
  2. 不需要将变量保持在关于要呈现的组件的状态。应根据父母的州
  3. render()计算
  4. 是的,回调是将信息传递给父母的推荐方式
  5. 代码质量看起来不错。你可以随时使用更漂亮或ESlint等工具。
  6. 以下是一个例子:

    class Main extends React.Component {
      constructor(props) {
        this.state = {
          stateA: '',
          stateB: '',
        };
      }
    
      handleStateChange(name, value) {
        this.setState({
          [name]: value,
        });
      }
    
      render() {
        const { stateA, stateB } = this.statel;
    
        const shouldRenderA = !stateA;
    
        if (shouldRenderA) {
          return <ComponentA value={stateA} onChange={value => this.handleStateChange('stateA', value)} />;
        }
        return <ComponentB value={stateA} onChange={value => this.handleStateChange('stateB', value)} />;
      }
    }
    
    class ComponentA extends React.Component {
      render() {
        const { value, onChange } = this.props;
    
        return <input type="text" value="value" onChange={onChange} />;
      }
    }
    
相关问题