【问题标题】:Redux using functional component without ReactRedux 使用没有 React 的功能组件
【发布时间】:2020-11-19 11:05:22
【问题描述】:

我有一个没有 React 但使用 Redux 的功能组件,如下所示:

export const isAuthenticated = () => ({user}) => {
    console.log("user : ", user);
    return true;
};

const mapStateToProps = (state) => {
    return {
        user: state.auth.userInfo
    }
}

export default connect(mapStateToProps)(isAuthenticated as any)

为了使用上述功能,我使用如下:

{isAuthenticated() && (
                        <li className="nav-item">
                            <NavLink
                                className="nav-link"
                                activeStyle={{
                                    color: "#1ebba3"
                                }}
                                to="/dashboard"
                                onClick={(e) => { if (this.menu.classList.contains("show")) { this.inputElement.click() } }}
                            >
                                Dashboard
                            </NavLink>
                        </li>
                    )}

它不起作用。它甚至没有进入那个 isAuthenticated 函数,因为我没有看到console.log("user : ", user); 的任何输出。它应该输出类似user: undefined 的内容,但它甚至不输出。

如果我改变了

export const isAuthenticated = () => ({user}) => {

export const isAuthenticated = ({user}) => {

那么问题是我不能用isAuthenticated() 调用它,并且可能是从函数调用传递的参数和从 Redux 检索的状态之间的重复。

如果我想继续使用“isAuthenticated()”来调用该方法,而不传递任何参数,但让 Redux 将用户状态传递给该函数,我该如何解决?

【问题讨论】:

标签: reactjs typescript redux react-redux react-functional-component


【解决方案1】:

这可以通过 React 的Hooks API 解决。您的目标是一个自定义钩子,它将在内部使用来自react-reduxuseSelector。如果你不想使用函数式组件,你可以随时选择Higher-Order Components (HOCs)

代码示例

自定义挂钩

import { useSelector } from 'react-redux';

export function useIsAuthenticated() {
    return useSelector(state => !!state.auth.userInfo);
}

export function YourComponent(props) {
    const isAuthenticated = useIsAuthenticate();

    // Return your react sub-tree here based on `isAuthenticated`
    // instead of `isAuthenticated()` like before.
}

高阶组件

import { connect } from 'react-redux';

export function withIsAuthenticated(Component) {
    function mapStateToProps(state) {
        return {
            isAuthenticated: !!state.auth.userInfo
        };
    }

    return connect(mapStateToProps)(function({ isAuthenticated, ...props }) {
        return <Component isAuthenticated={isAuthenticated} {...props}/>;
    });
}

export function YourComponent({ isAuthenticated, ...props }) {
    // Return your react sub-tree here based on `isAuthenticated`
    // instead of `isAuthenticated()` like before.
}

意见

就我个人而言,我觉得 HOC 引入的复杂性比必要的要多得多,如果我没记错的话,这是创建 Hook API 背后的主要驱动力之一。

【讨论】:

    猜你喜欢
    • 2021-06-09
    • 2020-08-07
    • 2023-04-10
    • 2020-04-08
    • 2020-09-18
    • 2019-08-06
    • 2020-05-23
    • 2017-10-14
    • 1970-01-01
    相关资源
    最近更新 更多