未处理的拒绝(错误):操作必须是普通对象。使用自定义中间件进行异步操作

时间:2018-03-21 02:01:36

标签: redux redux-thunk

我从api获取数据时无法调度操作。我正在尝试使用react和redux制作一个简单的todoapp并使用api获取数据。从api端点我返回一组任务和id。

    import React from 'react';
    import ReactDOM from 'react-dom';


    import  {createStore, applyMiddleware,compose} from 'redux';
    import thunk from 'redux-thunk';
    import {Provider} from 'react-redux';
    import logger from 'redux-logger';
    import reducers from './reducers/index';

    import {startSetTasks} from './actions/AddTask';
    import registerServiceWorker from './registerServiceWorker';
    import './index.css';
    import App from './App';
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

    const store = createStore(reducers,composeEnhancers(applyMiddleware(thunk)));


    const jsx=(
    <Provider store={store}>
    <App/>
    </Provider>);
    ReactDOM.render(<p>Loading...</p>, document.getElementById('root'))

    store.dispatch(startSetTasks()).then(() => {
        ReactDOM.render(jsx, document.getElementById('root'));
      }); 

动作生成器:我从api获取所有数据并尝试调度setTasks(),但它表示即使在使用redux-thunk后动作也必须是普通对象

        export const setTasks= (tasks)=>{
         type:'SET_TASKS',
         tasks
     }

    export const startSetTasks = ()=>{
        return (dispatch)=>{
          return fetch('http://localhost:4000/todo')
           .then((res)=>{
               return res.json()
           })
           .then((d)=>{
            const tasks=[];
            d.map((data)=>{
                tasks.push({
                    id:data._id,
                    task:data.task
            })

            });
            console.log('tasks ',tasks);
           dispatch(setTasks(tasks))

           }) 
        }
    };         

组件:我正在显示所有任务。我尝试使用connect

将startsetTasks()的返回数据作为道具发送
    import React from 'react';
    import {connect} from 'react-redux';
    import Task from './Task';
    import uuid from 'uuid';
    import {startSetTasks, startAddTask} from '../actions/AddTask'
    class TaskList extends React.Component {

        render() {


            return (
                <div>
                    <table>
                        <thead>
                            <tr>
                                <th>Tasks</th>
                                <th>Actions</th>

                            </tr>
                        </thead>
                        <tbody>
                            {this.props.tasks.map(({task,id})=>{
                                return <Task key={uuid()} task={task} id={id} />
                            })}
                        </tbody>
                    </table>
                </div>
            );
        }
    }

    const mapStateToProps = (state)=>{
        return{
            tasks:startSetTasks()
        }
    }

    export default connect(mapStateToProps)(TaskList);

减速器

switch(action.type)
    {
        case 'ADD_TASK': return  [...state, action.val];


        case 'DELETE_TASK': return state.filter(({id})=>{


            return id!==action.id;

        });
        case 'SET_TASKS':{
            return action.tasks
        }


        default: return state;
    }

};

const reducers= combineReducers({
    tasks:taskReducer
});

1 个答案:

答案 0 :(得分:0)

这是因为您的绑定操作错误。您尝试将操作作为属性进行存储,而不是作为组件中的操作。这是正确的代码示例:

import React from 'react';
import { connect } from 'react-redux';
import Task from './Task';
import uuid from 'uuid';
import { startSetTasks, startAddTask } from '../actions/AddTask'

class TaskList extends React.Component {
 componentDidMount() {
   this.props.startAddTask();
 }

 render() {
   return (
  <div>
    <table>
      <thead>
      <tr>
        <th>Tasks</th>
        <th>Actions</th>

      </tr>
      </thead>
      <tbody>
      {this.props.tasks.map(({ task, id }) => {
        return <Task key={uuid()} task={task} id={id}/>
      })}
      </tbody>
    </table>
  </div>
   );
 }
}
 const mapStateToProps = (state) => {
  return {
   tasks: state.tasks
  }
 };

  export default connect(mapStateToProps, { startAddTask })(TaskList);

注意我的组件导出语句;