ReactJS - prevState in the new useState React hook?

前端 未结 4 849
南方客
南方客 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: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:

提交回复
热议问题