动作必须是普通对象。使用自定义中间件进行异步操作

时间:2018-11-07 05:39:10

标签: reactjs redux react-redux axios

遇到Actions must be plain objects. Use custom middleware for async action错误:

Index Reducer:

import { combineReducers } from 'redux';
import ProfileReducer from './profile_reducer'

const rootReducer = combineReducers({
  user: ProfileReducer
});

export default rootReducer;

路线:

const createStoreWithMiddleware = applyMiddleware(promise)(createStore);

const Routers = () => (
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <Switch>
        <Route path='/' component={Home} exact={true}/>
        <Route path='/login' component={Login} exact={true}/>
        <Route path='/register' component={Login} exact={true}/>
        <PrivateRoute path='/profile' component={Profile} exact={true}/>
      </Switch>
    </BrowserRouter>
  </Provider>
);

导出默认路由器;

我正在尝试同时运行两个请求:一个请求从后端获取auth_token,并且在第一个请求的响应下,我运行另一个请求以获取用户的个人资料信息:

个人资料操作:

import axios from 'axios';

import { getAuthToken } from '../actions/auth';

const ROOT_URL = 'http://localhost:3000/api/v1';
export const FETCH_PROFILE = 'fetch_profile';

export function getProfile(values, callback) {
  const url = `${ROOT_URL}/profile`;

  getAuthToken( (res) => {
    const auth_token = res.data.auth_token
    const request = axios({
      method: 'GET',
      url: url,
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Authorization': `Token token=${auth_token}`
      },
    });

    // request.then((response) => {
    //   // callback(response);
    // })
    // request.catch((error) => {
    //   alert(error);
    // })

    return {
      type: FETCH_PROFILE,
      payload: request
    };
  });
}

我该怎么办?最好的方法和方法是什么?

0 个答案:

没有答案