问题
src/components/reducers/index.js
import {combineReducers} from 'redux';
const tasksReducer =(state=[] , action)=>{
switch(action.type){
case 'ADD_TASK':
state=state.concat(action.payload);
break;
case 'DELETE_TASK':
state=state.slice();
state.splice(action.payload,1);
break;
}
return state;
},
reducers=combineReducers({
tasks:tasksReducer
});
export default reducers;
(mapStateToProps() in Connect(Taskbar) must return a plain object. Instead received undefined.)
回答1:
src/index.js
here's how I've imported it..
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
//import * as serviceWorker from './serviceWorker';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import reducers from "./reducers/index";
let store=createStore(reducers);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
,
document.getElementById('root'));
回答2:
When using combineReducers() in your mapStateToProps you must specify the name of reducer the data you want to get come from. So, your mapStateToProps function should look like:
const mapStateToProps = state =>{
return {
PIECE_OF_STATE: state.tasks.PIECE_OF_STATE
}
}
Where tasks is the name of your reducer you declared in your combineReducer() function
回答3:
you should not directly mutate the state. I have not tried your whole code
import {combineReducers} from 'redux';
const tasksReducer =(state=[] , action)=>{
switch(action.type){
case 'ADD_TASK':
let tempArr = [...state];
let arr = tempArr.concat(action.payload); //action.payload is an array
return [...arr];
break;
case 'DELETE_TASK':
let tempArr= [...state];
tempArr.splice(action.payload,1);//action.payload is index
return [...tempArr];
break;
default:
return state;
}
};
export default combineReducers({
tasks:tasksReducer
});
here is a quick demo demonstrating array concat and splice
来源:https://stackoverflow.com/questions/58623981/redux-store-does-not-create