React Native 如何在redux中调用异步函数?

8wtpewkr  于 2023-02-13  发布在  React
关注(0)|答案(2)|浏览(132)

我已经按照这个教程,我认为我已经做了一切所需的,但我仍然有这个警告:
未处理的承诺拒绝: 错误:操作必须是普通对象。实际类型为:"Promise"。您可能需要向存储设置中添加中间件来处理其他值的分派,如"redux-thunk"来处理分派函数。有关示例,请参阅www.example.com和www.example.com。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 });
      });
  };
}
pcrecxhr

pcrecxhr1#

由于您提供的代码不一致,我不确定问题是什么:在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 });
}
tcomlyy6

tcomlyy62#

在状态管理中使用异步函数的更好方法是使用Redux-Thunk中间件,我认为这是最佳实践。
文档参见blow link:
Redux Thunk

相关问题