开发者问题收集

在 redux 中触发操作时,它说操作未定义

2016-11-20
81

我是 redux 的新手,正在用 redux 制作待办事项列表。我的动作创建器代码如下所示:

    /**
 * This file is called Action Creator (creates actions)
 *
 * Actions are objects as :
 * {
 *    type : 'ADD_TODO'     //the only thing needed is type
 *    text: 'this is our first to do'
 * }
 */

module.exports = {

  addTodo: function (text) {
    return (dispatch) => {
      dispatch({type: 'ADD_TODO', data: text});
    };
  }

};

//export default actions = {
//  addTodo(text) {
//    return {
//      type: 'ADD_TODO',
//      text: text
//    }
//  }
//};
//

我没有从动作返回对象,而是返回了一个函数。因此,在 store.js 文件中,我使用了 react-redux 中的 thunkMiddleware

我的 store.js 代码如下所示:

import { applyMiddleware, compose, createStore } from 'redux';
import reducer from '../reducers/reducers';
import thunkMiddleware from 'redux-thunk';

//We separated out the store from the client.js file so that if we have to add middleware here and change our state, we can do that here
//Add middlewares on actions here

let finalCreateStore = compose(
  applyMiddleware(thunkMiddleware)
)(createStore);

export default function configureStore(initialState = {todos: []}) {
  return finalCreateStore(reducer, initialState);
}

但是在触发操作时,它显示 操作未定义

[编辑]

我的 Reducer 如下所示:

function getId(state) {
  return state.todos.reduce((maxId, todo) => {
      return Math.max(todo.id, maxId)
    }, -1) + 1;
}

export default function reducer(state, actions) {
  switch (actions.type) {
    case 'ADD_TODO':
      Object.assign({}, state, {
        todos: [{
          //add new to do
          text: action.text,
          completed: false,
          id: getId(state)
        }, ...state.todos]
      });
      break;

    default:
      return state;
  }
}

此外,我还使用 connect 触发操作,如下所示:

function mapStateToProps(state) {
  return state;
}

function mapDispatchToProps(dispatch) {
  return {
    addTodo: (todo) => {
      dispatch(addTodo(todo));
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

我不知道如何摆脱这个错误。

2个回答

您的 Reducer 签名是 (state, action) ,但在函数主体中您有 action 。您可能指的是:

function reducer (state, action) {
   // code
}
azium
2016-11-20

您的 Reducer 中有一个拼写错误。您将 actions 定义为第二个参数,但在一行中(我在那里添加了注释),您尝试从未定义的 action 读取。

export default function reducer(state, actions) {
    switch (actions.type) {
        case 'ADD_TODO':
            Object.assign({}, state, {
                todos: [{
                    //add new to do
                    text: action.text, // <- action is not defined, but actions is
                    completed: false,
                    id: getId(state)
                }, ...state.todos]
            });
            break;

        default:
            return state;
    }
}

最好将其称为 action ,而不是 actions ,因为它只是一个动作。

ArneHugo
2016-11-20