我非常喜欢新的 React hooks,而且我在正在进行的项目中经常使用它们。我遇到了一种情况,我想在 useState hook 中使用 prevState,但我不太确定如何执行此操作。我尝试过类似这样的方法,但编译失败。
const [ someState, setSomeState ] = useState( new Map() ) setSomeState( prevState.someState.set( key, value ) )
(顺便说一下,这是为了映射复选框数组以跟踪已选中的复选框)我尝试遵循此处的示例,但不使用 setState 函数。
useState与功能挂钩一起使用useState:
useState
以下是如何
import React, { useState } from 'react'; const CheckboxMap = () => { const [someState, setSomeState] = useState(new Map()); const handleCheckboxChange = (key, value) => { setSomeState((prevState) => { const newMap = new Map(prevState); // Create a new Map based on the previous state newMap.set(key, value); // Set the new value return newMap; // Return the new Map }); }; // Example usage of the handleCheckboxChange function const handleCheckboxClick = (key) => { // Assume some logic to get the new value, e.g., checking/unchecking a checkbox const newValue = !someState.get(key); handleCheckboxChange(key, newValue); }; return ( <div> {<div> {/* Example checkboxes */} {['checkbox1', 'checkbox2', 'checkbox3'].map((key) => ( <label key={key}> <input type="checkbox" checked={!!someState.get(key)} onChange={() => handleCheckboxClick(key)} /> {key} </label> ))} </div> ); }; {[export default CheckboxMap; <label key={key}> <input type="checkbox" checked={!!someState.get(key)} onChange={() => handle <label key={key}> <input type="checkbox" che <
在此示例中:
someState
Map
setSomeState
handleCheckboxChange
这确保了状态更新