功能组件的setState中的prevState到底是什么?

时间:2020-02-07 05:20:49

标签: javascript reactjs state react-hooks react-state-management

setState钩子中获得的useState中返回(已更改的)先前状态似乎并没有改变状态。运行下面的简单代码段

function App(){
  const [state, setState] = React.useState([{x: 0}])
  function changeCount(){
    setState(prevState => {
      console.log('before', prevState[0])
      const newState = [...prevState]
      newState[0].x += 1 //the shallow copy newState could potentially change state
      console.log('after', prevState[0])//here x gets bigger as expected
      return prevState //instead of newState we return the changed prevState
    })
  }
  //checking state shows that x remained 0
  return <div className='square' onClick={changeCount}>{state[0].x}</div>
}
ReactDOM.render(<App/>, document.getElementById('root'))
.square{
  width: 100px;
  height: 100px;
  background: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<div id='root'></div>
通过单击正方形,我们触发setState。在setState中,我们复制先前状态的浅表newState。通过更改副本,我们在控制台确认时更改了prevState(可能是无意的)。但是,返回变化的先前状态形式setState不会改变状态,因为计数仍为0。如果我们返回newState,则行为将与预期的一样。

重复此操作,表明prevState变大了,它似乎不再代表以前的状态。

为什么?我在codepen ...

上做了一个最小的示例

1 个答案:

答案 0 :(得分:4)

考虑对象分配只是一个参考分配,绝不是副本

obj1 = {x:42, y:99};
obj2 = obj1;   // obj1 and obj2 both reference the same object
obj1.x += 1;   
obj2.y += 1;
console.log(obj1.x, obj1.y);
console.log(obj2.x, obj2.y);  // prints the same thing since obj1 and obj2 are the same object

在上面的示例中,obj1被初始化为指向具有属性x和y的新对象。制作obj2=obj1时,这不是obj1到obj2的副本,而是obj1和obj2现在引用了同一对象。

因此,在打印console.log语句时,它们将打印相同的内容,因为它们都是从同一对象打印属性值。

类似地,当从prevState到newState的浅表副本出现时,将对原始对象进行附加引用。

obj = {x:42, y:99};
prevState[0] = obj;     // prevState[0] is a reference to obj.  prevState[0] and obj point to the same exact thing

newState = [...prevState];  // shallow copy, but newState[0] is an object reference.  newState[0] and prevState[0] both point to "obj"

newState[0].x += 1;         // is actually updating the original object assigned to prevState[0]