前端
PythonJava运维数据库
状态管理
状态管理
  • 🖥️Redux Tookit
    • Introduction
      • 介绍
    • Tutorials
      • 🖥️快速开始
      • 🏐在TypeScript环境使用
    • Using Redux toolkit
      • 使用Immer编写Reducers
      • 性能与数据范式化
      • 异步逻辑与数据请求
      • Usage With TypeScript
    • API Refrence
      • Store Setup
        • configureStore
        • getDefaultMiddleware
        • Immutability Middleware
        • Serializability Middleware
        • Action Creator Middleware
        • createListenerMiddleware
        • createDynamicMiddleware
        • getDefaultEnhancers
        • autoBatchEnhancer
      • Reducer and Actions
        • createReducer
        • createAction
        • createSlice
        • createAsyncThunk
        • createEntityAdapter
        • combineSlices
      • Other
        • createSelector
        • Matching Utilities
    • RTX Query
      • RTK Query Overview
      • Comparson with Other Tools
      • Examples
      • Usage With TypeScript
      • Using RTK Query
        • Queries
        • Mutations
      • API Refrence
        • createApi
        • fetchBaseQuery
        • ApiProvider
        • setupListeners
        • Generated API Slices
          • Generated API Slices
          • Redux Integration
          • Endpoints
          • Code Splitting
          • Utilities
          • React Hooks
  • 🚚Redux-Saga
    • 入门
    • 基础概念
    • API
    • 技巧
  • 🚑React Redux
    • 安装
    • 教程
    • 使用 React Redux
    • API 参考
  • 🚕生态
    • Redux Persist
    • zustand
      • 使用 useShallow 防止重新渲染
由 GitBook 提供支持
在本页

这有帮助吗?

  1. 生态
  2. zustand

使用 useShallow 防止重新渲染

上一页zustand

最后更新于6个月前

这有帮助吗?

当您需要从 store 订阅状态时,推荐的方法是使用 selector。

如果输出根据 发生更改,计算选择器将导致重新渲染。

在这种情况下,如果计算值始终浅等于前一个值,您可能希望使用 useShallow 来避免重新渲染。

例子

我们有一家商店,每个人都有一顿饭,我们想呈现他们的名字。

import { create } from "zustand";

const useMeals = create(() => ({
    papaBear: "large porridge-pot",
    mamaBear: "middle-size porridge pot",
    littleBear: "A little, small, wee pot",
}));

export const BearNames = () => {
    const names = useMeals((state) => Object.keys(state));

    return <div>{names.join(", ")}</div>;
};

现在熊爸爸想要一份披萨:

useMeals.setState({
    papaBear: "a large pizza",
});

即使names的实际输出没有根据浅相等发生变化,此更改也会导致BearNames重新渲染。

我们可以使用useShallow来解决这个问题!

import { create } from "zustand";
import { useShallow } from "zustand/react/shallow";

const useMeals = create(() => ({
    papaBear: "large porridge-pot",
    mamaBear: "middle-size porridge pot",
    littleBear: "A little, small, wee pot",
}));

export const BearNames = () => {
    const names = useMeals(useShallow((state) => Object.keys(state)));

    return <div>{names.join(", ")}</div>;
};

现在,他们都可以订购其他餐点,而不会导致我们的BearNames组件不必要的重新渲染。

🚕
Object.is