【问题标题】:Using Middleware in react-hooks在 react-hooks 中使用中间件
【发布时间】:2019-08-27 05:47:15
【问题描述】:

所以我在我的 react-native 应用程序中使用 redux 进行状态管理。 我期待在我的应用程序中使用钩子。 我的商店有一个 reducer 的多个实例,因此将操作分派到单个 reducer 是一件很痛苦的事情。

在这种情况下,Hooks 似乎提供了一个非常巧妙的解决方案。 我们正在使用中间件来捕捉特定的动作并执行副作用。 我希望为钩子实现类似中间件的功能,其中分派给钩子的操作也可以在 redux-middleware 中捕获。

任何关于如何实现此类功能的建议都将受到高度赞赏。

谢谢。

【问题讨论】:

    标签: reactjs react-native redux react-redux react-hooks


    【解决方案1】:

    听说过或者你尝试过 redux-saga 用于你的中间件异步的事情,比如数据获取和不纯的事情,比如访问浏览器缓存,它更易于管理、更高效地执行、易于测试,并且更擅长处理故障。

    有关更完整的文档,您可以在 here 中查看

    我给你一个使用 redux saga 作为副作用的简单例子

    import api from '../api/apidetailproduct'; //if using api import it
    import {
        takeLatest, //Spawns a saga on each action dispatched to the Store that matches pattern
        select, //instructs the middleware to invoke the provided selector on the current Store's state
        call, //for calling api
        put //instructs the middleware to dispatch an action to the Store. 
    } from 'redux-saga/effects';
    import {
        REQUEST_PRODUCT, 
    } from '../actions/constants';
    import {
        responseProduct,
    } from '../actions/product';
    
    export function* detailEffect(){
        const {loginreducer} = yield select() //first select your reducer where you store
        try {
            const {data} = yield call(api, loginreducer.token )//calling the api and then send the variable
            yield put(responseProduct(data))//put the data
        } catch (error) {
            console.log("error", error);
        }
    }
    
    export const productsagas = [takeLatest(REQUEST_PRODUCT, detailEffect)]
    

    【讨论】:

    • 我不相信这个答案解决了这个问题。提问者想知道如何以类似于 Redux 的方式将 React hooks 与中间件结合使用。上面的答案为 Redux 提供了一个中间件,但没有提供有关如何将它或任何其他中间件应用到 React 钩子的信息。
    猜你喜欢
    • 2019-10-30
    • 2020-12-01
    • 2021-02-17
    • 2021-05-10
    • 2020-06-07
    • 2020-01-03
    • 1970-01-01
    • 2023-02-18
    • 2023-02-24
    相关资源
    最近更新 更多