我已经关注了这个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.
我的代码:
- 文件夹
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/