Mutating state from React's useState hook

前端 未结 1 1780
广开言路
广开言路 2021-01-04 20:19

Is it, and why is it a bad idea to mutate a state from React\'s new useState hook? I found no info on the topic.

Consider following code:

const [valu         


        
相关标签:
1条回答
  • 2021-01-04 20:51

    You should never mutate state directly as it might not even cause a re-render if you update the state with the same object reference.

    const { useState } = React;
    
    function App() {
      const [values, setValues] = useState({});
    
      const doSomething = (name, value) => {
        values[name] = value;
        setValues(values);
      };
    
      return (
        <div onClick={() => doSomething(Math.random(), Math.random())}>
          {JSON.stringify(values)}
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    
    <div id="root"></div>

    You can give a function as first argument to setValues just like you are used to in the class component setState, and that function in turn will get the correct state as argument, and what is returned will be the new state.

    const doSomething = (name, value) => {
      setValues(values => ({ ...values, [name]: value }))
    }
    

    const { useState } = React;
    
    function App() {
      const [values, setValues] = useState({});
    
      const doSomething = (name, value) => {
        setValues(values => ({ ...values, [name]: value }));
      };
    
      return (
        <div onClick={() => doSomething(Math.random(), Math.random())}>
          {JSON.stringify(values)}
        </div>
      );
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    
    <div id="root"></div>

    0 讨论(0)
提交回复
热议问题