Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am getting the [Error: Objects are not valid as a React child (found: object with keys {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;
question from:https://stackoverflow.com/questions/65918429/react-error-saying-objects-are-not-valid-as-react-child

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
226 views
Welcome To Ask or Share your Answers For Others

1 Answer

You probably try to render somewhere the counter? Your default case returns the entire object, instead of just 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...