如何在reactjs中管理有状态组件

时间:2017-07-27 08:03:47

标签: reactjs

我知道在大多数情况下使用无状态组件被认为是最佳实践,并且组件的逻辑和状态应保留在其父组件中。但问题是,如果另一个父组件需要具有相同的子组件(或其中一些组件),我们也必须在该父组件中重新创建相同的逻辑和状态。所以这就是我们拥有状态和有状态组件的原因,这样他们就可以管理自己的状态并管理自己的行为,以避免代码重复。

这种组件的一个很好的例子是Controlled input component。到目前为止一切都那么好,但我需要有一种方法来控制父组件的状态,例如我想清空它的值或自动更正它。为此,我们有componentWillReceiveProps()

class Input extends React.Component {
  static propTypes = {
    value: PropTypes.string,
    label: PropTypes.string,
  };

  static defaultProps = {
    value: '',
    label: '',
  };

  constructor(props) {
    super(props);
    this.state = { value: props.value };

    this.handleChange = this.handleChange.bind(this);
  }

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

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  render() {
    return (
      <label>
        {this.props.label}:
        <input type="text" value={this.state.value} onChange={this.handleChange} />
      </label>
    );
  }
}

因此Parent将新值传递给其Input组件,Input更新其componentWillReceiveProps函数中的状态。这里的问题是,现在我们必须始终在Input中保留Parent值。因为如果我们不传递它,那么它将从Input defaultProps获取,并且将无法再修改Input值。

我想要实现的是,如果Parent将值传递给Input,那么Input应该使用它并更新其状态。但是当它没有,但传递其他道具,那么Input应该保持自己的价值。

问题在于,componentWillReceiveProps函数无法判断道具是作为undefined传递还是等于defaultProps的值。一个可能的解决方案可能是根本不使用defaultProps。但是没有使用ReactJS这样的核心功能对我来说似乎不对。

0 个答案:

没有答案