【问题标题】:Update parent's state through callback prop from children (React.js)通过孩子的回调道具更新父母的状态(React.js)
【发布时间】:2015-06-19 15:27:25
【问题描述】:

我有一个使用 Form.jsx 组件的 Page.jsx

<Form isValid={this.enableButton} isInvalid={this.disableButton}>
  <Input validation={{ presence: true }} />
</Form>

重点是:Form 需要检查每个Input 的有效性才能继续。为了实现这一点,我在Form.jsx

// ...
allInputsAreValid: function () {
  return _.all(this.state.inputsValidation, function (inputsValidation) {
    return inputsValidation.error === false;
  });
}
// ...

那么,在Form.jsxrender方法中:

if (this.allInputsAreValid()) {
  this.props.isValid();
} else {
  this.props.isInvalid();
}

最后,方法enable/disableButton(在Form.jsx上):

// ...
enableButton: function () {
  this.setState({
    canSubmit: true
  });
},

disableButton: function () {
  this.setState({
    canSubmit: false
  });
}
//...

在这些方法中改变状态,控制台抛出错误:

未捕获的错误:不变违规:setState(...):在现有状态转换期间无法更新(例如在render 内)。渲染方法应该是 props 和 state 的纯函数。

为什么?如何解决?

【问题讨论】:

  • &lt;Form /&gt; 正在消耗来自Page.jsxenableButton / disableButton。当表单有效时——通过allInputsAreValid 方法检查——然后调用这些方法之一。关键是:从那里更改状态会导致该错误。

标签: javascript reactjs


【解决方案1】:

我假设“page.jsx”包含方法“enableButton”和“disableButton”。

在更新状态时,除了“canSubmit”之外,您还有其他状态属性吗?如果您有其他状态属性以及“canSubmit”,则通过执行

来强制它们变得未定义
  this.setState({
    canSubmit: true
  );

所以我假设存在一个名为“xyz”的状态属性以及“canSubmit”状态属性。所以像下面这样更新状态

this.setState({
    canSubmit: true,
    xyz:this.state.xyz
  );

或者更好的是你尝试使用 react update 插件来更新状态。更多在这里找到https://facebook.github.io/react/docs/update.html

更新

在您的 page.jsx 文件中尝试以下代码

  shouldComponentUpdate(object nextProps, object nextState){
     if(this.state.canSubmit==nextState.canSubmit){
        return false
     }
  }

【讨论】:

  • Uncaught TypeError: Cannot read property '_currentElement' of null — 不,到目前为止我只有canSubmit
  • 好的。尝试在 page.jsx 中包含“shouldComponentUpdate”方法
【解决方案2】:

您需要将此逻辑移出render 方法:

if (this.allInputsAreValid()) {
  this.props.isValid();
} else {
  this.props.isInvalid();
}

更新:

让我们修改您的 &lt;Input /&gt; 组件以接受 onChange 属性。我不确定你使用的是 ES6 类还是 React.createClass,但我会在这里走 ES6 类路线。

class Input extends React.Component {
  render() {
    return <input type="text" onChange={this.props.onChange} />;
  }
}

然后修改您的 Form.jsx 为输入提供onChange 属性。

<Form isValid={this.enableButton} isInvalid={this.disableButton}>
  <Input
    validation={{ presence: true }}
    onChange={() => {
      if (this.allInputsAreValid()) {
        this.props.isValid();
      } else {
        this.props.isInvalid();
      }
    }}
  />
</Form>

【讨论】:

  • componentDidMount 只出现一次。我需要检查每个状态的变化。
  • @GuilhermeOderdenge 我进行了更新。如果你不使用 ES6,请告诉我。
猜你喜欢
  • 2019-04-17
  • 2018-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
相关资源
最近更新 更多