react native使用zustand进行状态管理

发布时间 2023-10-11 15:32:58作者: Li_pk

1. 安装:

# NPM
npm install zustand

# Yarn
yarn add zustand

2. 创建store:

import { create } from "zustand";

const useStore = create((set) => ({
  count: 0,
  str: "",
  addCount: () => set((state) => ({ count: state.count + 1 })),
  setStr: (newStr) => set(() => ({ str: newStr })),
}));

export default useStore;

3. 组件内使用:

import {
  Button,
  View,
  Text,
} from 'react-native';
import { useStore } from "./store";
export default function Page() {
  const count = useStore((state) => state.count);
  const str = useStore((state) => state.str);
  const addCount = useStore((state) => state.addCount);
  const setStr = useStore((state) => state.setStr);

  const clickHandle = () => {
    addCount();
    setStr("a new string");
  }
  return (
    <View>
      <Text>{count}</Text>
      <Text>{str}</Text>
      <Button onPress={clickHandle} title="Click Button" color="#841584">点击</Button>
    </View>
  )
}

4. 外部文件中使用并获取更新状态

通过getState方法获取数据,通过subscribe方法订阅监听数据变更

import { useStore } from "./store";
const count = useStore.getState().count;
useStore.subscribe((newState) => {
  console.log(newState.count);
});

5. 更多

官方网址
文档地址