快速上手

一个基础的 React 应用示例,帮助你开始使用 TanStack react-store。

tsx
import React from "react";
import ReactDOM from "react-dom/client";
import { Store, useStore } from "@tanstack/react-store";

// 你也可以在 React 组件外部实例化 store!
export const store = new Store({
  dogs: 0,
  cats: 0,
});

// 仅当 `state[animal]` 变化时才会重新渲染。如果 store 中不相关的属性变化,则不会重新渲染

const Display = ({ animal }) => {
  const count = useStore(store, (state) => state[animal]);
  return <div>{`${animal}: ${count}`}</div>;
};

const updateState = (animal) => {
  store.setState((state) => {
    return {
      ...state,
      [animal]: state[animal] + 1,
    };
  });
};
const Increment = ({ animal }) => (
  <button onClick={() => updateState(animal)}>我的朋友喜欢{animal}</button>
);

function App() {
  return (
    <div>
      <h1>你的朋友中有多少人喜欢猫或狗?</h1>
      <p>
        按下面的按钮来增加喜欢猫或狗的朋友数量。
      </p>
      <Increment animal="dogs" />
      <Display animal="dogs" />
      <Increment animal="cats" />
      <Display animal="cats" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
import React from "react";
import ReactDOM from "react-dom/client";
import { Store, useStore } from "@tanstack/react-store";

// 你也可以在 React 组件外部实例化 store!
export const store = new Store({
  dogs: 0,
  cats: 0,
});

// 仅当 `state[animal]` 变化时才会重新渲染。如果 store 中不相关的属性变化,则不会重新渲染

const Display = ({ animal }) => {
  const count = useStore(store, (state) => state[animal]);
  return <div>{`${animal}: ${count}`}</div>;
};

const updateState = (animal) => {
  store.setState((state) => {
    return {
      ...state,
      [animal]: state[animal] + 1,
    };
  });
};
const Increment = ({ animal }) => (
  <button onClick={() => updateState(animal)}>我的朋友喜欢{animal}</button>
);

function App() {
  return (
    <div>
      <h1>你的朋友中有多少人喜欢猫或狗?</h1>
      <p>
        按下面的按钮来增加喜欢猫或狗的朋友数量。
      </p>
      <Increment animal="dogs" />
      <Display animal="dogs" />
      <Increment animal="cats" />
      <Display animal="cats" />
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);