react / redux - 在react-redux app中获取API

问题描述 投票:0回答:1

我是react和redux的新手,我正在检查一个购物车应用程序,如果我想从外部api获取这些虚拟对象该怎么办。我可以在反应中取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个回答
2
投票

当您使用fetch API时,您可以执行异步操作(对服务器的调用通常是异步的)。 redux不支持defualt的异步操作。所以你需要使用名为'thunk'或'redux-saga'的中间件(thunk更容易)这个中间件让你能够使用redux和异步动作。

thunk怎么工作?你创建一个返回函数的动作创建器而不是返回一个对象的acrion创建者。然后从商店传递给这个返回的函数调度函数。这使得返回的函数能够异步调用调度 - 作为回调

这是这个主题的最佳指南

thunk for dummy's

© www.soinside.com 2019 - 2024. All rights reserved.