問題描述
反應鉤子,不會將選中的屬性更改為複選框 (React hooks, does not change the checked property to checkbox)
我正在嘗試更改 ckeckbox 屬性,每次向地圖寫入新值時,在我單擊複選框時,它只會更改選中屬性的值,例如,初始值為是的,在所有後續點擊中,它將是錯誤的、錯誤的、錯誤的......這裡有什麼問題?
import React,{ useState,useEffect } from "react";
import {useSelector} from 'react‑redux'
const ChangeArticle = (props) => {
const prevArticle = props.changeArtcle;
const age_groups = useSelector(state => state.app.age_groups);
const [checkedAges, setCheckAges] = useState(new Map());
const handleChangeCheckBoxe = (event) => {
setCheckAges(checkedAges => checkedAges.set(event.target.value, event.target.checked));
console.log("checkedItems: ", checkedAges);
}
useEffect(() => {
if(prevArticle.ages){
prevArticle.ages.forEach((age) =>{
setCheckAges(checkedAges => checkedAges.set(age.toString(), true));
});
}
},[prevArticle]);
return (<div>
{age_groups.map(age => {
return (<div key={age.id}>
<input type="checkbox" checked={checkedAges.has(age.id.toString()) ? checkedAges.get(age.id.toString()) : false} value={age.id} onChange={handleChangeCheckBoxe}
/>
{ age.title }
</div>)
}) }
</div>);
}
export default ChangeArticle;
參考解法
方法 1:
In the handleChangeCheckBoxe
function, you are only changing the values withing the Map. React only does a shallow reference check to see if the Map had changed. Since the reference is the same, the it will not re‑render the component as you would expect.
You can change the function to be similar to the following to create a new Map and assign it to state.
const handleChangeCheckBoxe = (event) => {
setCheckAges(checkedAges => new Map(checkedAges.set(event.target.value, event.target.checked)));
console.log("checkedItems: ", checkedAges);
}
You can see this working in the following code sandbox https://codesandbox.io/s/wispy‑leftpad‑9sji0?fontsize=14&hidenavigation=1&theme=dark
(by Bob KapusAkba、nipuna777)