javascript - 如何在 redux 中调用异步函数?

标签 javascript reactjs react-native redux

我已经关注了这个tutorial我认为我已经按照要求完成了所有操作,但我仍然收到此警告:

Unhandled promise rejection: Error: Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.

我的代码:

  1. 文件夹store内这是我的index.js文件:
import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "../reducers/index";

const composedEnhancer = composeWithDevTools(applyMiddleware(thunkMiddleware)); 
const store = createStore(rootReducer, composedEnhancer);
export default store;

在我的 App.js 文件中:

...
import store from "./redux/store/index";
...
return (
        <Provider store={store}>
          <NavigationContainer>
            <MainNavigator />
          </NavigationContainer>
        </Provider>
      );

在我的 MainNavigator 文件中:

import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {someAsyncFunctionFromRedux} from "../../redux/actions/index";
...
const MainComponent = (props) => {
  ...

  useEffect(() => {
    async function f() {
      await props.someAsyncFunctionFromRedux();
    }
    f();
  }, []);

在我的actions/index.js

export async  function someAsyncFunction() {
   return  async (dispatch) => {
     await firebase
      .firestore()
      .collection("Users")
      .get()
      .then( (snapshot) => {
        let users = [];
        snapshot.docs.map((doc) => {
          const data = doc.data();
          const id = doc.id;
          users.push({id, ...data})
        })
        dispatch({ type: USERS_STATE_CHANGE, users });
      });
  };
}

最佳答案

我不太确定问题是什么,因为您提供的代码不一致:在 MainNavigator 中,您正在导入 someAsyncFunctionFromRedux 但您的示例代码仅有一个 someAsyncFunction。如果它是相同的函数并且只是示例是错误的,那么问题可能是您正在从异步函数返回异步函数。试试这个(有一些代码改进):

export async function someAsyncFunction(dispatch) {
  const snapshot = await firebase
    .firestore()
    .collection("Users")
    .get();
  const users = snapshot
    .docs
    .map(({ id, data }) => ({ id, ...data() }));
  dispatch({ type: USERS_STATE_CHANGE, users });
}

关于javascript - 如何在 redux 中调用异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75427344/

相关文章:

javascript - 在解构括号内赋值?

reactjs - 两个 useEffect 与一个 useEffect 内的两个 API 调用

user-interface - 当数组中元素的值发生变化时,React-Native 更新 UI,而不使用 ForceUpdate

javascript - Expo 身份验证从 Azure AD 接收无效 JWT

javascript - HTML元素的循环布局

javascript - apollo 服务器突变中无法使用 console.log() 函数

javascript - 动态命名部分 div 以备后用?

javascript - ng-重复未知数量的项目

reactjs - useEffect 派发问题(可能需要添加中间件)

reactjs - 使用 Enzyme 测试无状态 React 组件内的函数