我试图在更改时更改复选框状态,但它没有更改。它看起来像这张照片。这是我的InitialState
const initialState = {
isLoading: false,
showAlert: false,
products: [],
totalProducts: 0,
numOfPages: 1,
select: false,
};
这是我的上下文代码
const toggleProduct = (e) => {
const id = e.target.id;
dispatch({ type: TOGGLE_PRODUCT, payload: { id } });
};
还原剂
if (action.type === TOGGLE_PRODUCT) {
return {
...state,
products: state.products.map((product) => {
if (product._id === action.payload.id) {
return { ...product, select: !state.select };
} else {
return product;
}
}),
};
}
以及如何查看输入
<input
type='checkbox'
name={name}
defaultChecked={select}
id={_id}
onChange={toggleProduct}
/>
如果输入只是勾选了它不起作用,那么就不会选择输入,但如果defaultChecked,我可以选择输入,但是状态没有改变(请查看屏幕截图(。提前感谢
@jsN00b在评论中正确地指出,所有四个产品的检查状态都由一个单独的受控元素控制,即select key
,但通常情况下,每个产品都应该有自己的select属性,如下所示:
const initialState = {
isLoading: false,
showAlert: false,
products: [
// hard code the data for now
{_id: 1, productName: "productOne", select: false},
{_id: 2, productName: "productTwo", select: false},
{_id: 3, productName: "productThree", select: false},
],
totalProducts: 0,
numOfPages: 1
// select: false, ⬅ we don't need select in here now
};
// reducer
if (action.type === TOGGLE_PRODUCT) {
return {
...state,
products: state.products.map((product) => {
if (product._id === action.payload.id) {
return { ...product, select: !product.select }; // only toggle select for THE product
} else {
return product;
}
}),
};
}