繁体   English   中英

在redux中触发动作时,表示动作未定义

[英]On firing action in redux, it says action isn't defined

我是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);

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

你的化简签名是(state, actions)但是在功能体中你有action 您可能的意思是:

function reducer (state, action) {
   // code
}

减速器中有错别字。 您将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 ,因为它只是一个单一的动作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM