【问题标题】:React-redux, reducer unable to update state,error in codeReact-redux,reducer 无法更新状态,代码错误
【发布时间】:2020-08-09 10:35:32
【问题描述】:

我使用带有钩子和 redux 的 React JS 制作了一个简单的计数器代码,我可以在按钮点击时递增/递减计数器。编译时出现错误 Error: Objects are not valid as a React child (found: object with keys {count})。如果您打算渲染一组子项,请改用数组。

如果我删除 initialState 并声明 state=0 它工作正常,但我如何才能成功执行此代码以保持 initialState ?

let initialState ={
    count:0
}
const counter = (state=initialState,action)=>{
    switch(action.type){
        case 'INCREMENT': return {...state,count:state.count+1} ;
        case 'DECREMENT':return {...state,count:state.count-1};
        default: return state
    }
}

export default counter

我使用组件中的代码,如下所述

    const counter = useSelector(state=>state.counter)
           <h3>{counter}</h3> 
# note : some code parts are removed from this component for reader easiness 

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    state.counter 不是原始值,它是您保存在商店中 counter 字段下的对象。

    你可以更深一层:

    const counter = useSelector(state => state.counter.count);
    

    或者直接引用JSX里面count的值:

    <h3>{counter.count}</h3> 
    

    【讨论】:

      【解决方案2】:

      它是一个对象,所以你应该像这样破坏 count 属性:

      const {count } = useSelector(state=>state.counter)
       <h3>{count}</h3> 
      

      【讨论】:

        猜你喜欢
        • 2021-01-08
        • 2019-07-28
        • 2017-08-08
        • 2019-07-18
        • 2018-08-04
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        • 2017-03-22
        相关资源
        最近更新 更多