[英]update state delay in checkbox, React
我必须对象newProduct
sizes
我需要使用复选框设置可用尺寸,它工作正常但是:
When I check two boxes, the state updates only in the first box, then when pushing the sizes
object to the newProduct
object, the state on the newProduct
did not update until I check the third box (update only the value of the first box)
这是我的代码:
function Products(){
const [sizes, setSizes] = useState({
s: false, m: false, l: false, xl: false, xxl: false, xxxl: false
})
const [newProduct, setNewProduct] = useState({
productType : "", name : "", price : "", photo : "", sizes : sizes
})
const manageSizes = (e) => {
const { name, checked} = e.target
setSizes({...sizes, [name] : checked}) // late (1)
setNewProduct({...newProduct, sizes : sizes}) // late (2)
}
return (
{Object.keys(sizes).map((item, index) => (
<label key={index} htmlFor={item}>{item}
<input
type="checkbox"
checked={sizes[item]}
name={item}
onChange={manageSizes}
/>
</label>
))}
)
}
您需要在设置新产品时使用新的 object。
const manageSizes = (e) => {
const { name, checked} = e.target
setSizes({...sizes, [name] : checked})
setNewProduct({...newProduct, sizes : {...sizes, [name] : checked}}) // <--- new object.
}
或将其设置为新变量
const manageSizes = (e) => {
const { name, checked} = e.target
const newSizes = {...sizes, [name]: checked }
setSizes(newSizes)
setNewProduct({...newProduct, sizes : newSizes }) // <--- new object.
}
由于setSizes
是异步的 function,所以无法在 setSizes 之后立即获取更新后的sizes
值。
您应该在useEffect
中通过添加sizes
依赖项来获得它。
useEffect(() => {
setNewProduct({...newProduct, sizes: sizes})
}, [ sizes ])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.