自定义中间件错误,即使在实施后

时间:2019-05-19 18:07:22

标签: javascript reactjs redux redux-thunk

我正在通过Async-Await使用API​​调用,这需要自定义中间件,我正在使用Thunk作为自定义中间件。已安装所有依赖项。然后,由于某种原因,它无法检测到中间件或类似的东西。

我的代码在执行时显示以下错误: Error Page

这是我的 Actions 页面:我使用了Async-Await,这导致我遇到此错误

import axios from "axios";

export const saveTwitterToken = (token) => {
  return ({
    type: TWITTER_OAUTH,
    payload: token
  });
};

export const callTwitterAPI = async (config) => {
  const request = await axios({
    "url": "https://api.twitter.com/1.1/statuses/home_timeline.json",
    "method": "GET",
    "headers": {
      "Authorization": " _Something_ "
    }
  });
  return ({
    type: "api",
    payload: request
  })
};

这是我的 Index.js 页面:

import React from "react";
import ReactDOM from "react-dom";
import App from './App'
import {Provider} from "react-redux";

import 'bootstrap/dist/css/bootstrap.css';
import stores from "./utils/store";

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

这是自定义中间件商店文件:

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

import reducers from '../reducers';

const store = createStore(
  reducers,
  {},
  compose(
    applyMiddleware(thunk)
  )
);
export default store;

1 个答案:

答案 0 :(得分:0)

您必须对异步Redux Action使用调度,如下所示:

export const callTwitterAPI = config => async dispatch => {
  const request = await axios({
    "url": "https://api.twitter.com/1.1/statuses/home_timeline.json",
    "method": "GET",
    "headers": {
      "Authorization": " _Something_ "
    }
  });

  dispatch({
    type: "api",
    payload: request
  })
}

更好的方法是使用promise,如下所示:

export const callTwitterAPI = config => dispatch => {
  axios({
    "url": "https://api.twitter.com/1.1/statuses/home_timeline.json",
    "method": "GET",
    "headers": {
      "Authorization": " _Something_ "
    }
  }).then(request =>
     dispatch({
       type: "api",
       payload: request
     })
  ).catch(error => handle it OR dispatch another action)
}

希望对您有帮助。