javascript - 关于没有中间件的 Redux Async (redux-thunk, redux-saga...)

标签 javascript reactjs redux redux-thunk redux-saga

有些 Action 有异步功能,比如fetch。但是,我不想使用像 redux-thunk 或 redux-saga 这样的中间件。 所以,我犹豫要不要使用这个代码。

/* actions */

...

export const fetchRequest = ({category, query, dispatch}) => ({
    type: actionTypes.FETCH_REQUEST,
    promise:
        fetch(`${API_URL}${category}?${query}`, {headers: headers})
        .then(response => response.json())
        .then(data => dispatch(fetchRecieve(data))),
})

export const fetchRecieve = data => ({
    type: actionTypes.FETCH_RECIEVE,
    data,
})

...

/* In x.jsx */
...

const mapDispatchToProps = dispatch => ({
onClick: (category, query) => dispatch(fetchRequest({category, query, dispatch}))
})

...

此代码是否违反了 Redux 范式?

最佳答案

Redux FAQ "How can I represent “side effects” such as AJAX calls?..

In general, Redux suggests that code with side effects should be part of the action creation process. While that logic can be performed inside of a UI component, it generally makes sense to extract that logic into a reusable function so that the same logic can be called from multiple places—in other words, an action creator function.

您发布的功能是 Action 创建者,因此放置它们似乎是一个合适的地方,但是在下一段中他们说:

The simplest and most common way to do this is to add the Redux Thunk middleware that lets you write action creators with more complex and asynchronous logic. Another widely-used method is Redux Saga which lets you write more synchronous-looking code using generators, and can act like “background threads” or “daemons” in a Redux app. Yet another approach is Redux Loop, which inverts the process by allowing your reducers to declare side effects in response to state changes and have them executed separately. Beyond that, there are many other community-developed libraries and ideas, each with their own take on how side effects should be managed.

您有什么理由反对使用 redux-thunk、redux-saga、redux-loop 等吗?它们的存在都是为了真正帮助你。您可以选择手动执行副作用,但在 IMO 中使用中间件执行它的管理较少。

关于javascript - 关于没有中间件的 Redux Async (redux-thunk, redux-saga...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354988/

相关文章:

javascript - 如何在选中复选框时获取不同表中的表行数据?

javascript - 为什么 React 钩子(Hook)在 React 文档中使用 const?

javascript - 如何避免改变 this.state 或 redux 对象

javascript - React + Redux Prop 没有及时加载

javascript - 使javascript动画条与动画百分比同步

javascript - 如何在收到 websocket 消息时更新从 RTK 查询返回的 Hook 数据

javascript - 使用这个 .charAt() 的任何替代方法?

javascript - 单击按钮时如何将按钮的值添加到文本区域?

javascript - 在 React/Flux 应用程序中,延迟操作超时属于哪里?

javascript - Spread 运算符动态属性更新