ReactJS - prevState in the new useState React hook?

前端 未结 4 850
南方客
南方客 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条回答
  • 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 (
        <div>
          <h5>Updates Second key to 'not empty'</h5>
          <p>First key: {object.firstKey}</p>
          <p>Second key: {object.secondKey}</p>
          <p>Third key: {object.thirdKey}</p>
          <button onClick={withPrevState}>
            Update with prevState
          </button>
          <button onClick={() => {setObject({secondKey: 'not empty'})}}>
            Update without prevState
          </button>
          <button onClick={() => {setObject(initialState)}}>
            Reset
          </button>
        </div>
      );
    };
    
    // Render it
    ReactDOM.render(
      <Example />,
      document.getElementById("react")
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
    <div id="react"></div>

    0 讨论(0)
  • 2021-01-31 18:16

    You have already the previous state in the destructed variable: someState

    so you can do:

    const [ someState, setSomeState ] = useState( new Map() )
    setSomeState( someState.set( key, value ) )
    
    0 讨论(0)
  • 2021-01-31 18:22

    In order to use Map objects, you'll need to clone it before manipulating the values. Otherwise, it's mutating the original Map object and React doesn't handle mutatable state.

    const handleChange = useCallback(({ target: { name, checked } }) => {
      setCheckbox(prevState => {
        return new Map(prevState).set(name, checked);
      });
    }, []);
    

    Updated Working Example:

    0 讨论(0)
  • 2021-01-31 18:28

    state updater from useState provides a callback pattern which returns you the previous state which you can use to update the current state

    const [ someState, setSomeState ] = useState( new Map() )
    setSomeState(prevState => prevState.set( key, value ) )
    
    0 讨论(0)
提交回复
热议问题