我的reducer中有两种情况:
case GET_CODE:
return {
...state,
list:[...state.list,{code: action.payload.product.Code}]
}
case WEIGHT:
return {
...state,
list:[...state.list,{weight:action.payload}]
}
我的状态是这样的:
list: [
{ weight: ''},
{weight: '100'},
{weight: '200'},
{code: '63'},
{code: '64'}
]
我想要的是:
list: [
{weight: ''},
{weight: '100', code:'63'},
{weight: '200', code:'64'}
]
我的初始状态是list:[]
。我认为权重的第一个空值来自初始渲染。我先发送WEIGHT,然后发送GET_CODE操作。
您应该编写某种帮助函数来为您创建对象,或者代码/权重用例应该在list
中找到它应该对应的对象。
对于助手功能:
const createObject = (code, weight) => {
const obj = {code: code.product.Code, weight: weight}
dispatch({type: 'ADD_TO_LIST', payload: obj});
}
// In your reducer
case ADD_TO_LIST:
return {
...state,
list: [
...state.list,
action.payload
]
}
或者只使用ADD_TO_LIST大小写并在reducer 中创建对象
即
case ADD_TO_LIST:
return {
...state,
list: [
...state.list,
{code: action.payload.code.product.Code, weight: action.payload.weight}
]
}