繁体   English   中英

使用父组件的道具设置状态

[英]Set State with Props from Parent Component

有没有一种方法来设置stateComponentPropsComponent从接收Parent Component?

export default class SomeComp extends Component {
    constructor(props) {
        super(props);

        this.state = someProps; // <-- I need the props to be the state of the Component
    }


    render() {
        const { someProps } = this.props;
        ...
    }
}

或者我可以写一个函数,比如

export default class SomeComp extends Component {
    constructor(props) {
        super(props);

    }

    _setProps = (someProps) => {
          this.State = someProps;
    }

    render() {
        const { someProps } = this.props;
        this._setProps(someProps);
        ...
    }
}

正如Mayank Shukla所提到的,将父道具存储在孩子状态是不好的做法,从而管理孩子内的状态。

将道具传递给孩子的整个想法是,你不必关心孩子内部的状态,因为这一切都是从父母那里流下来的。

子组件应该只关心它们的状态。

您应该做什么(以及什么是好的反应实践)是在父组件中具有状态并将事件处理程序传递给将改变父项状态的子项。

// in parent
class MyParentComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      data: someData;
    };
  }

  handleChange(data) {
    this.setState(data);
  }

  render() {
    return (
      <MyChildComponent
        data={this.state.data}
        handleChange={this.handleChange}
      />
    );
  }
}



class MyChildComponent extends React.Component {
  // this is going to update the data in parent
  // and trickle it back down to the child
  this.props.handleChange({ foo: 'bar' });
}

建议将孩子状态保持在父组件中。 所以parent.state最终会包含children节,其中孩子们的状态可以存储在唯一的id下。

this.state = {
     title: 'Some title',
     // other local stateful attributes
     children:{
        kidId1:{
          kidAttr1:' 'value'
        },
        ....
        kidId100:{
          kidAttr1:' 'value'
        }
     }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM