[英]React-redux, reducer unable to update state,error in code
I made a simple counter code using React JS with hooks and redux where I can increment/decrement counter on button clicks.我使用带有钩子的 React JS 和 redux 制作了一个简单的计数器代码,我可以在按钮点击时增加/减少计数器。 When compiling I get error Error: Objects are not valid as a React child (found: object with keys {count}).
编译时出现错误Error: Objects are not valid as a React child (found: object with keys {count})。 If you meant to render a collection of children, use an array instead.
如果您打算渲染一组子项,请改用数组。
If I remove initialState and declare state=0
it works fine, but how can I execute this code successfully be keeping initialState?如果我删除 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
I consume the code in a component as mention below我使用组件中的代码,如下所述
const counter = useSelector(state=>state.counter)
<h3>{counter}</h3>
# note : some code parts are removed from this component for reader easiness
The state.counter
isn't a primitive value, it's an object that you keep in your store under counter
field. state.counter
不是原始值,它是一个 object,您可以将其保存在您的商店中的counter
字段下。
You can either go one level deeper:您可以 go 更深一层:
const counter = useSelector(state => state.counter.count);
or directly refer to the count
value inside JSX:或者直接参考JSX里面的
count
值:
<h3>{counter.count}</h3>
It is an object so you should distruct the count property like this:它是一个 object 所以你应该像这样破坏 count 属性:
const {count } = useSelector(state=>state.counter)
<h3>{count}</h3>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.