Redux/thunk Error: Actions must be plain objects. Use custom middleware for async actions

Redux/thunk Error: Actions must be plain objects. Use custom middleware for async actions

我是 Redux 的新手,并已按照此视频 https://www.youtube.com/watch?v=93p3LxR9xfM 将 Redux 实施到我的 MERN 模板中,但是由于 "Error: Actions must be plain objects. Use custom middleware for async actions."

它一直崩溃

我认为问题可能出在调度函数的某处,但似乎无法找到它。

获取文件:

   `export function fetchPosts () {
    return function(dispatch) {
     fetch('http://localhost:5000/products/5d082bb89501e113334e5c8e')
     .then(res => res.json())
     .then(posts => dispatch({
      type: FETCH_POSTS,
      payload: posts
       })
   );
  }
 } `

组件: class MyComponent 扩展 React.Component { componentWillMount() { this.props.fetchPosts(); }<br> 使成为() { return ( <div></div> ); } }; 导出默认连接(null, { fetchPosts })(MyComponent);

fetchPosts 操作 return 是一个函数,而它被期望 return 是一个普通对象。

redux 中的异步操作需要返回一个函数。但是你需要连接一个名为 redux-thunk.

middleware

https://github.com/reduxjs/redux-thunk

这样,这个错误就会消失。


如何接线redux-thunk:

import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'

import rootReducer from './reducers'

const store = createStore(
  reducers, // your reducers
  compose(
    applyMiddleware(thunk)
  )
)