[英]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.