【问题标题】:use custom hook in redux reducer在 redux reducer 中使用自定义钩子
【发布时间】:2020-08-09 11:13:13
【问题描述】:

有没有办法在我的 redux reducer 中使用自定义的 react hook?

我想在我的 switch 案例中调用 getDistanceHandler() 或 useGetDistance(),但 React 告诉我不允许在函数组件的主体之外使用钩子

在 pastebin 上查看代码:https://pastebin.com/jqhK9zee

import {
...
SET_FILTERS,
...
} from '../actions/lokale';
import Lokal from './../../models/lokal';
import useGetDistance from '../../handler/useGetDistance';

const initialState = {
...
filteredLokale: [],
...
};

const getDistanceHandler = useGetDistance();

const lokaleReducer = (state = initialState, action) => {
switch (action.type) {
    ...
    case SET_FILTERS:
        //TODO
        const filters = action.filter;
        const updatedFilteredLokale = state.lokale.filter((lokal) => {
            let bool = true;
            //Name
            if (filters[0]) {
                bool = lokal.name.toLowerCase().indexOf(filters[0].toLowerCase()) > -1;
            }
            //Category
            if (bool && filters[1]) {
                bool = lokal.category.toLowerCase().indexOf(filters[1].toLowerCase()) > -1;
            }

            if (bool && filters[2]) {
                getDistanceHandler(region.latitude, region.longitude).then((distance) => {
                   bool = distance <= filters[2];

                }); 
            }

            return bool;
        });
        return { ...state, filteredLokale: updatedFilteredLokale };

    ...
    default:
        return state;
}
};

export default lokaleReducer;

【问题讨论】:

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


    【解决方案1】:

    Hooks 是 React 的一个特性。它们使用 React API,并且完全由 React 组件生命周期管理。在 React 组件中调用时唯一执行任何类型的逻辑功能。尝试在 React 组件之外使用钩子是没有意义的。

    【讨论】:

    • 您建议如何存储此代码,以便我可以在我的 react 组件和 redux reducer 中使用? pastebin.com/68VbaE0G
    • 这个有什么解决方案吗?
    • 我遇到了需要使用钩子函数(react intl)进行翻译的问题,所以我的快速解决方法是调用钩子函数,获取返回值并将其作为操作负载传递。
    猜你喜欢
    • 2020-10-01
    • 2020-08-28
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2021-12-23
    • 2019-07-05
    相关资源
    最近更新 更多