尝试遵循教程时无法击败"Actions must be plain objects. Use custom middleware for async actions."错误 redux.js.org



我正在努力学习redux.js.org上的redux教程。我偶然发现"操作必须是普通对象。将自定义中间件用于异步操作"错误。这没有意义,因为我的操作确实是普通对象(至少我认为是这样(,所以我不应该被迫使用任何中间件。(我尝试使用thunk也失败了,但这不是这个问题的关注(

以下是我的动作创作者:

export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_FILTER = 'SET_FILTER'
export const VisibilityFilters = {
SHOW_ALL: 'SHOW_ALL',
SHOW_COMPLETED: 'SHOW_COMPLETED',
SHOW_ACTIVE: 'SHOW_ACTIVE'
}
export function addTodo(todoText) {
return 
{
type: ADD_TODO
todoText
}
}
export function toggleTodo(index) {
return
{
type: TOGGLE_TODO
index
}
}
export function setFilter(filter) {
return 
{
type: SET_FILTER
filter
}
}

我的减速器:

import { combineReducers } from 'redux'
import { 
ADD_TODO,
TOGGLE_TODO,
SET_FILTER,
VisibilityFilters 
} from '../actions'
const { SHOW_ALL } = VisibilityFilters
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [
...state,
{
text: action.text,
completed: false
}
]
case TOGGLE_TODO:
return state.map((todo, index) => {
if (index === action.index) {
return Object.assign({}, todo, {
completed: !todo.completed
})
}
return todo
})
default:
return state
}
}
function visibilityFilter(state=SHOW_ALL, action) {
switch(action.type) {
case SET_FILTER:
return action.filter
default: 
return state
}
}
const todoApp = combineReducers({
visibilityFilter,
todos
})
export default todoApp

最后是index.js(main(:

import React from 'react'
import ReactDOM from 'react-dom'
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { createStore } from 'redux';
import todoApp from './reducers';
import {
addTodo,
toggleTodo,
setFilter,
VisibilityFilters
} from './actions';

const store = createStore(todoApp)
// Log the initial state
console.log(store.getState())
// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
const unsubscribe = store.subscribe(() =>
console.log(store.getState())
)
// Dispatch some actions
store.dispatch(addTodo('Learn about actions'))   // This line causes the error.
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setFilter(VisibilityFilters.SHOW_COMPLETED))
// Stop listening to state updates
unsubscribe()
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

如果你能帮我拨乱反正,让我继续我的Redux之旅,我将不胜感激。

您必须将返回对象制动器放在的同一行

export function addTodo(todoText) {
return {
type: ADD_TODO
todoText
}
}

相关内容

最新更新