【问题标题】:Custom Middleware error even after implemented即使在实施后自定义中间件错误
【发布时间】:2019-05-19 18:07:22
【问题描述】:

我正在使用需要自定义中间件的 Async-Await API 调用,我使用 Thunk 作为自定义中间件。已安装所有依赖项。然后,不知何故,它无法检测到中间件或类似的东西。

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

这是我的 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;

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    你必须使用 dispatch 进行异步 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)
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-30
      • 2022-08-14
      • 2021-06-30
      • 2021-12-04
      • 2015-02-08
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多