Prevstate in `this.setState` - copy or link?

I tried to figure this out for a while and did not find the right answer.

In the following code:

this.setState(prevState => counter: prevState.counter + 1);

Is there a prevStatelink to the current state? Or is it a copy of it? Is it possible to mutate or mutate correctly?

+7
source share
2 answers

From the documents ...

prevState is a reference to a previous state. So should not be directly mutated. Instead, changes should be presented by creating a new object based on the input from prevState and props.

https://facebook.imtqy.com/react/docs/react-component.html

So, to answer your question, prevState is a condition before the last mutation has occurred.

+7

, prevState IS . , , prevState - , .

:

. , , , , , , , .

function App() {
  
  const[myState,setMyState] = React.useState({propA: 'FOO'});
  
  function handleClick() {
    setMyState((prevState) => {
      console.log('myState: ' + JSON.stringify(myState));
      console.log('prevState: ' + JSON.stringify(prevState));
      console.log('Are "myState" and "prevState" the very same object: ' + JSON.stringify(prevState === myState));
      const shallowCopy = {...prevState}
      console.log('shallowCopy of prevState: ' + JSON.stringify(shallowCopy));
      console.log('Are "shallowCopy" and "prevState" the very same object: ' + JSON.stringify(shallowCopy === myState));
      return prevState;
    });
  }
  
  function updateWithShallowCopy() {
    setMyState((prevState)=>{
      const shallowCopy = {...prevState};
      shallowCopy.propA = 'BAR<-------------------------------------';
      return shallowCopy;
    });
  }
  
  function updateWithoutShallowCopy() {
    setMyState((prevState)=>{
      prevState.propA = 'BAR';
      return prevState;
    });
  }
  
  return(
    <React.Fragment>
      <div>{myState.propA}</div>
      <button onClick={handleClick}>Click to inspect</button>
      <button onClick={updateWithoutShallowCopy}>Update WITHOUT shallow copy</button>
      <button onClick={handleClick}>Click to inspect</button>
      <button onClick={updateWithShallowCopy}>Update WITH shallow copy</button>
      <div>Click in all buttons in order from left to right</div>
    </React.Fragment>
  );
}


ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
Hide result
0

Source: https://habr.com/ru/post/1683459/


All Articles