redux 操作必须是普通对象,实际类型为:'promise'----已使用形实转换

r6vfmomb  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(87)

我已经使用了thunk中间件,但仍然得到错误,这是为什么?-------我错过了什么?x1c 0d1x
App.js

useEffect(() => {
    dispatch(getPosts())
  }, [dispatch])

操作文件:

import * as api from "../api/index"

export const getPosts = async dispatch => {
    try {
        const { data } = await api.fetchPosts()
        dispatch({ type: "GET_ALL", payload: data })
    } catch (error) {
        console.log(error)
    }

异径管文件:

export const reducers = (posts = [], action) => {
    switch (action.type) {
        case "GET_ALL":
            return action.payload

        default:
            return posts
    }
}

存储文件:

import thunk from "redux-thunk";
import { reducers } from "../reducers/index"
import { createStore, applyMiddleware, compose } from 'redux';

const store = createStore(reducers, compose(applyMiddleware(thunk)))
export default store
pcrecxhr

pcrecxhr1#

这里有一个thunk,而不是thunk操作创建器。
所以要么你做

dispatch(getPosts)

或者你有

export const getPosts = () => async dispatch => {

也就是说,你在这里写的是一个非常过时的Redux风格--在现代Redux中(自2019年起),你不能手动写开关... case reducer,ACTION_TYPES,不可变的reducer逻辑或动作创建器。你也不应该使用createStore(现在已经被弃用),composeapplyMiddleware
请阅读Why Redux Toolkit is How To Use Redux Today. Modern Redux大约是代码的1/4。
你可能正在学习一个非常过时的教程,我建议你学习official Redux Tutorial

相关问题