ReactJS - 新的 useState React 钩子中的 prevState? [英] ReactJS - prevState in the new useState React hook?
问题描述
我真的很喜欢新的
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屋!