首页 > 解决方案 > 使用 thunk 的 React-Redux 异步函数不起作用

问题描述

Types.js 文件:

const ADD_TOKENS = "ADD_TOKENS";

export { ADD_TOKENS};

Actions.js 文件:

import { ADD_TOKENS } from "./types";

function addTokens() {
  return {
    type: ADD_TOKENS,
  };
}

const actionCreators = {
  addTokens,
};

export { actionCreators };

Reducers.js 文件

import { ADD_TOKENS } from "./types";
import getTokens from "../../api/getTokens";

const initialState = {
  access_token: null,
  refresh_token: null,
  expiration_time: null,
};

function applyAddTokens(state) {
  console.log("Function being hit"); //yes
  return async (dispatch) => {
    console.log("Function being hit"); //no
    const token = await getTokens();
    return {
      ...state,
      access_token: dispath(token.access_token),
      refresh_token: dispath(token.refresh_token),
      expiration_time: dispath(token.expiration_time),
    };
  };
}

function reducer(state = initialState, action) {
  switch (action.type) {
    case ADD_TOKENS:
      return applyAddTokens(state);
    default:
      return state;
  }
}

export default reducer;

index.js 文件

import React, { Component } from "react";
import { View, Text, TouchableOpacity } from "react-native";

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { actionCreators as actions } from "./actions";

class Login extends Component {
  render() {
    const { addTokens } = this.props;
    console.log("Props in Login/index.js", this.props);
    return (
      <View>
        <TouchableOpacity onPress={addTokens}>
            <Text>Login</Text>
          </TouchableOpacity>
      </View>
    );
  }
}

function mapStateToProps(state) {
  const { access_token, refresh_token, expiration_time } = state;
  return {
    access_token,
    refresh_token,
    expiration_time,
  };
}

function mapDispatchToProps(dispatch) {
  return {
    addTokens: bindActionCreators(actions.addTokens, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Login);

store.js 文件

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "../components/Login/reducers";

const store = createStore(reducer, applyMiddleware(thunk));

export default store;

为什么这不起作用?为什么applyAddTokens函数的 thunk 没有产生任何东西?让我知道是否有人需要任何其他详细信息。getTokens()返回一个包含 access_token、refresh_token 和 expire_time 的对象。这在我在没有异步的情况下尝试它之前有效(只是没有任何请求的常规数据)。

标签: reactjsreact-nativereduxreact-redux

解决方案


您的代码流程如下所示:

  • 在您的 JSX 中,在 onPress 时,您触发 action addTokens
  • 此操作返回一个类型的对象ADD_TOKENS
  • Redux 会直接执行 reducer(ADD_TOKENSswitch case)。在这里,您正在调用异步函数applyAddTokens
  • Redux 将立即执行它(无需等待 promise 结果)并返回函数的输出,applyAddTokens该函数是pending promise
  • 而已。

解决方案


推荐阅读