React-RTK:Selector unknown returned a different result when called with the same parameters.

在 React 项目中,使用 redux-toolkit 编写 Redux 逻辑,有如下代码:

// store/hooks
import { TypedUseSelectorHook, useSelector, useDispatch } from 'react-redux';
import type { RootState, APPDispatch } from "./index";

// 在整个应用程序中使用,而不是简单的 `useDispatch` 和 `useSelector`
export const useAppDispatch: () => APPDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

// RoleTab 组件中
import { useAppDispatch, useAppSelector } from "../../../../store/hooks";
const RoleTab = () => {
	// 这行代码导致的报错
	const tabList = useAppSelector(state => state.tabInfo.tabList || []);
	// 其他代码...
}

执行代码之后,报错如下:

useSelector.ts:205:Selector unknown returned a different result when called with the same parameters. This can lead to unnecessary rerenders. Selectors that return a new reference (such as an object or an array) should be memoized.
翻译过来就是:
当使用相同的参数调用时,未知选择器返回不同的结果。 这可能会导致不必要的重新渲染。新引用应该被缓存。

const tabList = useAppSelector(state => state.tabInfo.tabList || []);

在上述代码中,当 tate.tabInfo.tabList 是 undefined 时,tabList 是 [];当 tate.tabInfo.tabList 有实际值之后,tabList 是 实际值,tabList 的引用发生了改变,在 reduc-toolkit 中,更新 state 时不能更新引用。

解决方案:

const tabList = useAppSelector(state => state.tabInfo.tabList) || [];

你可能感兴趣的:(TypeScript,React,react.js,前端,typescript)