【问题标题】:why initial state is not retaining in react-redux为什么初始状态没有保留在 react-redux 中
【发布时间】:2021-09-30 01:03:46
【问题描述】:

在“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 的初始状态被从状态中删除。 请让我哪里出错了。 提前致谢,

【问题讨论】:

    标签: reactjs redux react-redux react-router react-hooks


    【解决方案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;
        }
    }
    

    【讨论】:

    • 谢谢罗伯托,这解决了问题。但是初始 ...state 有什么用(在信息之前: [...state.info, ..action.payload] )以及为什么每个人都在使用它?
    • 那是为了复制你的 reducer 不关心的其他状态属性。想象一下,如果你还有另一个 otherInformation 属性,除了 information
    • 好的明白了,谢谢帮助。
    猜你喜欢
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2016-03-09
    相关资源
    最近更新 更多