ReactJS - prevState in the new useState React hook?

前端 未结 4 913
南方客
南方客 2021-01-31 17:45

I really like the new React hooks and I\'m using them frequently for a project I\'m working on. I\'m coming across a situation where I want to use the prevState in the

4条回答
  •  不要未来只要你来
    2021-01-31 18:05

    For objects you can use the spread operator to use prevState within your setState call.

    const [stateObject, setObjectState] = useState({
      firstKey: '',
      secondKey: '',
    });
    
    setObjectState((prevState) => ({
      ...prevState,
      secondKey: 'value',
    }));
    
    // stateObject = {
    //   firstKey: '',
    //   secondKey: 'value',
    // }
    

    The snippet below show an example of using prevState for setting the state of an object.

    const {useState} = React;
    
    const Example = ({title}) => {
      const initialState = {
        firstKey: 'empty',
        secondKey: 'empty',
        thirdKey: 'not empty',
      }
      const [object, setObject] = useState(initialState);
      
      const withPrevState = () => {
        setObject((prevState) => ({
          ...prevState,
          secondKey: 'not empty',
        }));
      }
    
      return (
        
    Updates Second key to 'not empty'

    First key: {object.firstKey}

    Second key: {object.secondKey}

    Third key: {object.thirdKey}

    ); }; // Render it ReactDOM.render( , document.getElementById("react") );
    
    
    

提交回复
热议问题