Mutating state from React's useState hook

前端 未结 1 1794
广开言路
广开言路 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 (
        
    doSomething(Math.random(), Math.random())}> {JSON.stringify(values)}
    ); } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

    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 (
        
    doSomething(Math.random(), Math.random())}> {JSON.stringify(values)}
    ); } ReactDOM.render(, document.getElementById("root"));
    
    
    
    

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