如何使用多个值更新反应状态以及如何通过回调函数依赖该更新状态。能行吗

时间:2018-09-24 00:07:14

标签: javascript reactjs react-redux

我正在尝试更新对象post的状态。值应来自titleentry格式字段,其状态正确且实时地设置。这不是调用setState回调函数的正确方法吗?我认为问题所在是更新状态的异步部分,但是我对JS不够熟悉,无法真正了解这里发生的情况。任何帮助,将不胜感激。

class EditForm extends React.Component {
 initialState = {
 title: (this.props.posts.find(el => el.id === this.props.id)).title,
 entry: (this.props.posts.find(el => el.id === this.props.id)).entry,
 post: this.props.posts.find(el => el.id === this.props.id)
}

state = {...this.initialState}

handleChange = (e) => {
 const { name, value } = e.target
 this.setState({ [name]: value })
}

handleSubmit = (e) => {
 e.preventDefault()
 this.setState(prevState => ({
  post: {
      ...prevState.post,
      title: this.state.title,
      entry: this.state.entry
  }
}), this.nowSubmit())
}

nowSubmit = () => {
 console.log(this.state.post)
 this.props.dispatch(updatePost(this.state.post))
 this.props.closeForm()
}

1 个答案:

答案 0 :(得分:0)

您快到了,但是回调不正确:)

如果您尝试以下方式:

this.setState(prevState => {
    return {
        post: {*variables*}
    }
}, this.nowSubmit)

或者,只要简短,就将简单函数放在() => {this.nowSubmit function}中:)

这与您要内联使用函数时必须在构造函数中绑定函数的情况相同。如果您想了解更多原因,请告诉我:)