【问题标题】:react/redux - Fetch API in react-redux appreact/redux - 在 react-redux 应用程序中获取 API
【发布时间】:2019-02-07 12:02:33
【问题描述】:

我是 react 和 redux 的新手,我正在检查一个购物车应用程序,如果我想从外部 api 获取这些虚拟对象怎么办。我可以在 react 中获取 api,但 redux 让我有点困惑。

productsReducer.js

const INIT_PRODUCTS = [
    {id:1, title: 'Watch', description: 'Lorem Ipsum', price: 80, img:''},
    {id:2, title: 'Watch', description: 'Lorem Ipsum', price: 50, img:''},
    {id:3, title: 'Watch', description: 'Lorem Ipsum', price: 35, img:''}
];
export default function productsReducer(state=INIT_PRODUCTS, action={}) {

    function findProductIndex(products, id) {
        return products.findIndex((p) => p.id === id)
    }

    return state;
}

【问题讨论】:

标签: reactjs rest api redux react-redux


【解决方案1】:

当您使用 fetch API 时,您会执行异步操作(对服务器的调用通常是异步的)。 redux 默认不支持异步操作。 所以你需要使用名为“thunk”或“redux-saga”的中间件(thunk 更容易) 这个中间件使您能够使用带有异步操作的 redux。

thunk 是如何工作的?您创建一个返回函数的动作创建者,而不是返回对象的 acrion 创建者。 然后你将 store 中的 dispatch 函数传递给这个返回的函数。这使返回的函数能够异步调用调度 - 作为回调

这是该主题的最佳指南

thunk for dummy's

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 2019-07-15
    • 2021-09-27
    • 2016-11-09
    • 2016-06-11
    • 2016-10-24
    • 2017-11-22
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多