选择器在调用时会返回根状态。Redux 工具包

Ahm*_*eem 5 react-native redux-toolkit

我每次运行我的应用程序时都使用 reduxtoolkit 的 useSelector 。我的应用程序重新渲染了 5 次,并且不断收到此错误。我似乎找不到一种方法来摆脱这个错误。

选择器在调用时会返回根状态。这可能会导致不必要的重新渲染。返回整个状态的选择器几乎肯定是一个错误,因为每当状态发生任何变化时它们都会导致重新渲染。

错误图像

AppNavigator.tsx

const AppNavigator: FC<Props> = props => {
  const {loggedIn, busy} = useSelector(getAuthState);
  const dispatch = useDispatch();
  console.log('render');
  useEffect(() => {
    const fetchAuthInfo = async () => {
      try {
        dispatch(updateBusyState(true));
        const token = await getFromAsyncStorage(Keys.AUTH_TOKEN);
        if (!token) {
          return dispatch(updateBusyState(false));
        }

        const {data} = await client.get('/auth/is-auth', {
          headers: {
            Authorization: 'Bearer ' + token,
          },
        });
        dispatch(updateProfile(data.profile));
        dispatch(updateLoggedInState(true));
      } catch (error) {
        console.log('Auth error: ', error);
      }
      dispatch(updateBusyState(false));
    };
    fetchAuthInfo();
  }, []);

  return (
    <NavigationContainer theme={AppTheme}>
      {busy ? (
        <View
          style={{
            ...StyleSheet.absoluteFillObject,
            backgroundColor: colors.OVERLAY,
            zIndex: 1,
            justifyContent: 'center',
            alignItems: 'center',
          }}>
          <Loader />
        </View>
      ) : null}
      {loggedIn ? <TabNavigator /> : <AuthNavigator />}
    </NavigationContainer>
  );
};
Run Code Online (Sandbox Code Playgroud)

切片.tsx

const slice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    updateProfile(authState, {payload}: PayloadAction<UserProfile | null>) {
      authState.profile = payload;
    },
    updateLoggedInState(authState, {payload}) {
      authState.loggedIn = payload;
    },
    updateBusyState(authState, {payload}: PayloadAction<boolean>) {
      authState.busy = payload;
    },
  },
});

export const {updateLoggedInState, updateProfile, updateBusyState} =
  slice.actions;

export const getAuthState = createSelector(
  (state: RootState) => state,
  ({auth}) => auth,
);

export default slice.reducer;
Run Code Online (Sandbox Code Playgroud)

phr*_*hry 13

对于像您在这里所做的事情,您确实不需要(也不应该使用)createSelector

代替

export const getAuthState = createSelector(
  (state: RootState) => state,
  ({auth}) => auth,
);
Run Code Online (Sandbox Code Playgroud)

你可以写

export const getAuthState = (state: RootState) => state.auth;
Run Code Online (Sandbox Code Playgroud)

createSelector仅当您的选择器正在进行大量计算或创建新对象时才需要。

另外,你不应该做类似的事情

export const getAuthState = (state: RootState) => state.auth;
Run Code Online (Sandbox Code Playgroud)

state.auth.profile.lastName当(或者实际上是 中的其他任何内容)发生变化时,它也会重新渲染state.auth

相反,做

const {loggedIn, busy} = useSelector(getAuthState);
Run Code Online (Sandbox Code Playgroud)