[英]why initial state is not retaining in react-redux
在操作“ADD_CONTACT”之后,新状态在 redux 中更新,但初始状态不会恢复,即使我使用扩展运算符添加初始状态。
这是我的减速器:
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 的初始状态被从状态中删除。 请让我哪里出错了。 提前致谢,
您没有使用简化状态的当前状态值:
export const productReducer = (state = initalstate, action)=>{
switch (action.type) {
case "ADD_CONTACT":
state = {
...state,
information : [...state.information, ...action.payload] // Combine them
}
default:
return state;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.