我想了解ReactJS中的SetState和Prevstate

时间:2018-11-30 17:20:59

标签: javascript reactjs

我是ReactJS的新手,我在项目中使用向导表单,使用户可以进行下一步和上一步操作。我为下一步按钮复制了一些代码,但老实说不明白这是什么意思。

能否请您帮助我理解以下代码:

next() {
    this.setState(prevState => ({ current: prevState.current + 1 }));
}

2 个答案:

答案 0 :(得分:3)

感谢您的贡献。

正如评论中建议的那样,您可能应该看看documentation,但是由于您是新撰稿人,所以我想我会尝试回答您的问题。

状态和setState如何工作

每个组件的反应类别都有一个“状态”。更新“状态”后,组件将重新渲染。 setState是用于更新组件状态的方法。 this是指组件本身。

您的组件state对象最初看起来像这样:{ current: 0, something: 'foo' }

next()在做什么

当您致电next()时,还将同时呼叫setStatesetState通过回调进行调用。回调提供了一个参数,这里名为prevState-prevState是组件上的当前state,因此{ current: 0, something: 'foo' }

返回值setState将设置状态对象上提供的任何字段。调用this.setState后,component.state的新值将为{ current: 1, something: 'foo' }

重新渲染

由于新状态和先前状态对象的浅表比较将返回false,因此将触发组件的重新呈现。

希望这会有所帮助!

答案 1 :(得分:1)

正如我在评论中提到的那样,您需要查看文档本身才能进一步了解how setState works

在这里,我想说明为什么我们需要它?

在反应状态下不可变,即。说你不能像这样直接改变状态:

state = { current: 1 }
// ...and somewhere in your code
this.state.current = 2 // won't work
this.state.current = this.state.current + 1 // also, no luck
console.log(this.state.current) // 1
// the reason is immutable

因此,您需要更新状态而不对其进行更改。因此,React提供了公开使用setState的功能。

setState有两个参数:updater和callback。

更新器可以接受状态和道具。这样一来,您就可以根据状态和道具或其他方式更新状态,以检查其状态。

在setState中提供了此回调,因此您可能像现在current一样了解其效果。请参见下面的示例:

this.setState((state, props) => { // previous state, previous props
  // you may additionally check some condition
  // or combine state and props
  // like, state.current + props.value
  return { current: state.current + 1 }
}, () => {
// ^^- callback
  console.log(this.state.current)
})

顺便说一句,有一些不同的选项可以使用setState:

a) without updater and callback
eg. setState({current: 2})
b) with updater param only
eg. setState(()=>({current: 2}))
c) with updater and callback
eg. see preceding example of code
d) without updater but with callback
eg.  setState({current: 2},()=>console.log(this.state.current))
相关问题