Redux store does not create

☆樱花仙子☆ 提交于 2020-02-06 06:40:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!