自学内容网 自学内容网

React 第三方状态管理库相关 -- Recoil & Zustand 篇

 一、Recoil

首先安装依赖:

npm install recoil

示例代码:

// src/store/index.js
import { countState } from './counterState';

export {
    countState
};
// src/store/counterState.js
import { atom } from 'recoil';

export const countState = atom({
    key: 'countState',
    default: 0,
});
// src/main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.jsx'
import { RecoilRoot } from 'recoil';

createRoot(document.getElementById('root')).render(
  <StrictMode>
    <RecoilRoot>
      <App />
    </RecoilRoot>
  </StrictMode>,
)
// src/App.jsx
import React from 'react';
import { useRecoilState } from 'recoil';
import { countState } from './store';

const App = () => {
  const [count, setCount] = useRecoilState(countState);

  return (
    <div>
      <h1>Counter</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
};

export default App;

二、Zustand

首先安装依赖:

npm install zustand

示例代码:

// src/store/index.js
import useCounterStore from "./counterStore";

export { useCounterStore };
// src/store/counterStore.js
import { create } from 'zustand';

const useCounterStore = create((set) => ({
    count: 0,
    increment: () => set((state) => ({ count: state.count + 1 }))
}));

export default useCounterStore;
// src/App.jsx
import React from 'react';
import { useCounterStore } from './store';

const App = () => {
  const counterStore = useCounterStore();
  console.log(counterStore);

  return (
    <div>
      <p>Count: {counterStore.count}</p>
      <button onClick={() => counterStore.increment()}>Increment</button>
    </div>
  );
};

export default App;


原文地址:https://blog.csdn.net/weixin_59685936/article/details/145172793

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!