为什么初始状态没有在 react-redux 中保留
2021-07-22
273
在操作“ADD_CONTACT”之后,新状态在 redux 中得到更新,但即使我使用扩展运算符添加初始状态,初始状态也不会反映出来。
这是我的 Reducer:
const initalstate = {
information : [
{
key: 1,
name: "firstname"
}
]
}
export const productReducer = (state = initalstate, action)=>{
switch (action.type) {
case "ADD_CONTACT":
state = {...state , information : action.payload,}
console.log("state :", state)
default:
return state;
}
}
这是我的调度函数:
const updatedata = [
{ id : "2", name : "secondname" },
{ id : "3", name : "thirdname"}
]
export const Footer = () => {
const data = updatedata;
const currentState = useSelector(state => state)
const dispatch = useDispatch()
const handSubmit = (data)=>{
dispatch(
{ type : "ADD_CONTACT",
payload :data } )
console.log(currentState)}
return (
<div className="btn">
<button onClick={()=>{handSubmit(data)}}>add</button>
</div>
)
}
id 2 和 3 已添加,但包含 id 1 的初始状态已从状态中删除。 请告诉我我哪里做错了。 提前致谢,
1个回答
您没有将当前状态值用于简化状态:
export const productReducer = (state = initalstate, action)=>{
switch (action.type) {
case "ADD_CONTACT":
state = {
...state,
information : [...state.information, ...action.payload] // Combine them
}
default:
return state;
}
}
Roberto Zvjerković
2021-07-22