redux 中的动作是否需要调度?

Is dispatch needed in an action in redux?

我学习 redux 有一段时间了,想知道为什么在 action 中需要 dispatch,我们不能只使用 return,这不是一回事吗?

  return {
    type: SEARCH_MOVIE,
    payload: text,
  };
};

export const fetchMovies = (text) => (dispatch) => {
  axios
    .get(`https://www.omdbapi.com/?apikey=${APIKey}&s=${text}`)
    .then((response) =>
      dispatch({
        type: FETCH_MOVIES,
        payload: response.data.Search,
      })
    );
};

第一个action是没有dispatch的,它正常工作,为什么我们需要在其他函数中使用dispatch,我们不能只使用return? 我只需要有人向我解释 dispatch 在一个动作中做了什么,我以后无论如何都会在我的组件中以某种方式或 onClick 分派。为什么我们需要分派它两次?

那是一个 thunk when using the redux-thunk 图书馆。

With a plain basic Redux store, you can only do simple synchronous updates by dispatching an action. ...

Thunks are the recommended middleware for basic Redux side effects logic, including ... simple async logic like AJAX requests.

  • action,在 redux 词汇表中,只是一个对象,例如
    {type: 'a1'},
  • action creator 是一个 returns 动作的函数,例如
    (value) => ({type: 'a1', valye})
  • thunk of action 是一个将调度函数作为参数并调用它的函数,例如
    (dispatch) => { dispatch({type: 'a1'}) }。配合redux-thunk中间件,可以在任何需要动作的地方使用。
  • action creator 的函数 (a) returns 函数 (b) 因此 (b) 是 thunk 的action 在 (a) 的闭包中创建,例如
    (value) => (dispatch) => { dispatch({type: 'a1', value}) }

当使用 redux-thunk 时,简单的 action creatorthunk of an action creator 可以互换使用,你不不必在不需要时使用 (dispatch) => ...(异步操作或更复杂的逻辑需要从一个函数分派多个操作)。