Reactjs React redux子项使用上下文或简单选择

Reactjs React redux子项使用上下文或简单选择,reactjs,redux,react-redux,react-hooks,Reactjs,Redux,React Redux,React Hooks,我有一个父母使用 const isAuthenticated = useSelector(selectIsAuthenticated); 使用相同的选择器的最佳方法是什么 在孩子身上 或者使用上下文提供程序,如 母公司 孩子 const isAuthenticated=useContext(AuthContext) 通常,您可以重复使用选择器,因为它只是一个函数 export const selectIsAuthenticated = state => state.isAuthe

我有一个父母使用

const isAuthenticated = useSelector(selectIsAuthenticated);
使用相同的选择器的最佳方法是什么

在孩子身上

或者使用上下文提供程序,如

  • 母公司

  • 孩子

    const isAuthenticated=useContext(AuthContext)


通常,您可以重复使用选择器,因为它只是一个函数

export const selectIsAuthenticated = state => state.isAuthenticated;

// Usage
import { selectIsAuthenticated } from './auth-selectors.js'

const isAuthenticated = useSelector(selectIsAuthenticated);
或者将其重新用作自定义挂钩:

import { selectIsAuthenticated } from './auth-selectors.js'

export const useAuth = () => {
  const isAuthenticated = useSelector(selectIsAuthenticated);
  // more auth related code ...
  return { isAuthenticated };
};

// usage

const { isAuthenticated } = useAuth();

要获取身份验证信息,最好的方法是使用

const isAuthenticated = useSelector(selectIsAuthenticated);
在所有需要身份验证信息的地方(这也是第一个地方的自定义挂钩的目的),在一个地方有一个通用的重用逻辑

为相同的信息创建另一个上下文不会带来任何好处

在这两种情况下,无论您再次使用上下文还是选择器挂钩,只有上下文的使用者才会呈现


因此,在所有位置使用useSelector钩子可以省去再次创建上下文的额外麻烦,而这无论如何都不会带来任何额外的好处。

为什么不在child中使用useSelector呢?这取决于您。如果您已经通过Redux获得了它,那么可能没有必要引入另一个上下文来传递它。您甚至可以为此创建自己的钩子,例如
constuseuseauthenticated=()=>useSelector(selectIsAuthenticated)