简体   繁体   English

反应错误说对象作为反应子无效

[英]React error saying Objects are not valid as react child

I am getting the [Error: Objects are not valid as a React child (found: object with keys {counter, num}).我收到 [错误:对象作为 React 子对象无效(找到:object 和键 {counter, num})。 If you meant to render a collection of children, use an array instead.] error for the below code:如果您打算渲染一组子项,请改用数组。] 以下代码的错误:

const initialState = {
    counter: 0,
    num : 0
}
const counterReducer = (state = initialState, action) => {
    switch(action.type){
        case "INCREMENT":
            {
                return {
                    ...state,
                    counter: state.counter + action.payLoad
                }
            }
            case "DECREMENT":
                return {
                    ...state,
                    counter: state.counter - action.payLoad
                }
        default:
            {
                return state;
            }
    }
}
export default counterReducer;

If I do like below everything working fine:如果我喜欢以下一切正常:

const counterReducer = (state = 0, action) => {
    switch(action.type){
        case "INCREMENT":
            return  state + action.payLoad;
        case "DECREMENT":
            return state - action.payLoad;
        default:
            {
                return state;
            }
    }
}

export default counterReducer;

You probably try to render somewhere the counter?您可能尝试在某个地方渲染柜台? Your default case returns the entire object, instead of just state.counter .您的默认案例返回整个 object,而不仅仅是state.counter Try it like this:试试这样:

const counterReducer = (state = initialState, action) => {
switch(action.type){
    case "INCREMENT":
        {
            return {
                ...state,
                counter: state.counter + action.payLoad
            }
        }
        case "DECREMENT":
            return {
                ...state,
                counter: state.counter - action.payLoad
            }
    default:
        {
            return state.counter;
        }
    }
}

Or in the component where you render it access the object property state.counter或者在渲染它的组件中访问 object 属性state.counter

There's nothing wrong with the reducer you've written.你写的reducer没有问题。

Without the corresponding component code and based on the error you're seeing, it seems that you're using the entire state object ( { counter: 0, num: 0 } , for example) within the React component that's using the state from this reducer.如果没有相应的组件代码,并且根据您看到的错误,您似乎正在使用 state object (例如{ counter: 0, num: 0 } )在使用 Z9ED369E2EA96341586 的这个 React 组件中的整个 state减速器。

Replacing the object ( { counter: 0, num: 0 } , from the above example) with just the counter value ( obj.counter ) should get it working仅用计数器值( obj.counter )替换 object ( { counter: 0, num: 0 } ,来自上面的例子)应该让它工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM