Answer the question
In order to leave comments, you need to log in
Redux - "Objects are not valid as a React child" error when combining reducers via combineReducers. How can I fix it?
I am making a preparation for a project with the union of several reducers (for now, the reducer is 1).
When trying to use combineReducers, it throws an error:
Objects are not valid as a React child (found: object with keys {counterReducer}). If you meant to render a collection of children, use an array instead.
in div (at Counter.js:10)
in Counter (created by Connect(Counter))
in Connect(Counter) (at index.js:50)
in Provider (at index.js:49)
// src/store/counter/reducer.js
export default function counterReducer(state = 0, action) {
switch (action.type) {
case 'ADD':
return state + action.step;
case 'REMOVE':
return state - action.step;
default:
return state;
}
}
// src/store/reducers.js
import { combineReducers } from 'redux';
import counterReducer from './counter/reducer';
export default combineReducers({
counterReducer
});
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import Counter from './components/Counter';
import counterReducer from './store/counter/reducer';
import reducer from './store/reducers';
let store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.getElementById('root'));
// src/components/Counter.js
import React from 'react';
import { connect } from 'react-redux';
import { add, remove } from '../store/counter/actions';
function Counter(props) {
const { count, add, remove } = props;
return (
<div>
<button onClick={() => add(5)}> +5 </button>
<button onClick={() => add(1)}> +1 </button>
{count}
<button onClick={() => remove(1)}> -1 </button>
<button onClick={() => remove(5)}> -5 </button>
</div>
);
}
function mapStateToProps(state) {
return {
count: state,
};
}
function mapDispatchToProps(dispatch) {
return {
add: step => dispatch(add(step)),
remove: step => dispatch(remove(step)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
// src/store/counter/action.js
export function add(step){
return {type: 'ADD', step:step}
}
export function remove(step){
return {type: 'REMOVE', step:step}
}
Answer the question
In order to leave comments, you need to log in
Please post more component code and if you are using react-redux, then connect call code.
By mistake, it looks like you're passing a simple object somewhere as a child component, like {props} instead of {props.children}.
show the code where you use the reducer. it feels like you just inserted counterReducer
into the method render
of some component
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question