ReactJS - 新的 useState React 钩子中的 prevState? [英] ReactJS - prevState in the new useState React hook?

查看:39
本文介绍了ReactJS - 新的 useState React 钩子中的 prevState?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢新的

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 useState hook, but I'm not really certain on how to do this.

I've tried something like this, but it fails to compile.

const [ someState, setSomeState ] = useState( new Map() )
setSomeState( prevState.someState.set( key, value ) )

(by the way, this is to map an array of checkboxes to keep track of the ones that are check marked)

I'm trying to follow this example here, but without using the setState function.

Thanks for the help!

解决方案

In order to use Maps, you'll need to clone it before manipulating the values. Otherwise, it's mutating the original Map 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:

这篇关于ReactJS - 新的 useState React 钩子中的 prevState?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆