无法将状态传递给 React 中的动作创建者

Cannot pass state to action creator in React

这是表格

<PostBody>
  <Input value={this.state.title} onChange={(value) => this.onChangeTitle(value)} ref="titleInput" type="text" id="title" name="title" placeholder="Post Title" />
  <TextArea value={this.state.body} onChange={(value) => this.onChangeBody(value)} ref="bodyInput" id="body" name="body" placeholder="Post Content" />
  <ToolBar>
    <Button disabled={!this.props.ptitle || !this.props.pbody} onClick={this.props.doSave(this.state)}>Save</Button>
    <BackLink to="/posts">Cancel</BackLink>
    <div style={{float:'left', marginTop:'10px'}}>
      {backBtn}
    </div>
  </ToolBar>
</PostBody>

下面是我调用动作创建函数的方式

doSave: (state) => {
   dispatch(savePostAction(state));
},

但这会导致错误

warning.js:36 Warning: setState(...): Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

并无限次击中导致

Uncaught RangeError: Maximum call stack size exceeded

我什至尝试在单击时调用另一个函数,然后通过传递该函数的状态来调用 doSave()。仍然出现相同的错误。请帮忙。

在您的变体中,当组件正在渲染时,您无需单击即可调用函数。 将 onClick={this.props.doSave(this.state)} 更改为 onClick={() => this.props.doSave(this.state)}

原因是,onClick 期望 function,您不需要调用它 function,它会在单击按钮时被调用。

onClick={this.props.doSave(this.state)}

此处 doSave 将在每次渲染时调用,无需点击。

所以代替:

onClick={this.props.doSave(this.state)}

使用:

onClick={() => this.props.doSave(this.state)}