API
import axios from "axios"
const url = "http://localhost:5000/posts"
export const fetchPosts = () => async () => await axios.get(url)
export const createPost = async (post) => await axios.post(url, post)
行动
export const fetchPosts = async (dispatch) => {
try {
const {data} = await api.fetchPosts()
dispatch({
type: types.FETCH_POSTS,
payload: data
})
} catch (err) {
console.error(err)
}
}
商店
import { createStore, applyMiddleware } from 'redux'
import rootReducer from './index'
import thunk from 'redux-thunk'
export default function configureStore() {
return createStore(rootReducer, applyMiddleware(thunk))
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'
import configureStore from './Redux/store/configureStore'
const store = configureStore();
ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
我想通过 axios 对我的帖子发出获取请求。 post request没有问题,但是我获取不到。
useEffect(() => {
dispatch(fetchPosts())
}, [dispatch])
当我使用这个方法时它会抛出这个错误:
错误:操作必须是普通对象。相反,实际类型是:'Promise'。您可能需要将中间件添加到您的商店设置中以处理调度其他值,例如“redux-thunk”以处理调度功能。
没有任何语法或导入/导出错误。
为什么即使我插入 redux thunk 来存储它也会抛出这个中间件错误?
最佳答案
你需要更新fetchPosts
返回一个函数
export const fetchPosts = () => async (dispatch) => {
try {
const {data} = await api.fetchPosts()
dispatch({
type: types.FETCH_POSTS,
payload: data
})
} catch (err) {
console.error(err)
}
}
关于reactjs - useEffect 派发问题(可能需要添加中间件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68209982/