• Rematch官网
  • 使用Rematch可以使全局状态管理更加的简单和方便
  • 这里只做基本使用介绍,具体可查阅官网
  • 这里的使用是在react hooks组件中

一、安装rematch

  • npm install @rematch/core
  • npm install react-redux

二、rematch使用

  • 新建文件models/count.js

import { createModel } from "@rematch/core";export const sharks = createModel()({state: 0,reducers: {increment: (state, payload) => state + payload,},effects: (dispatch) => ({async incrementAsync(payload) {await new Promise((resolve) => setTimeout(resolve, 1000));dispatch.sharks.increment(payload);},}),
});
  • 新建文件models/index.js

import { sharks } from "./sharks";export const models = { sharks };
  • 新建文件store.js

import { init } from "@rematch/core";
import { models } from "./models";export const store = init({ models });
  • index.js配置

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import App from "./App";
import { store } from "./store";ReactDOM.render(<React.StrictMode><Provider store={store}><App /></Provider></React.StrictMode>,document.getElementById("root")
);
  • 获取与修改全局状态值App.jsx

import React from "react";
import { useDispatch, useSelector } from "react-redux";export default function App() {const sharks = useSelector((state) => state.sharks);const dispatch = useDispatch();return (<div><div>{sharks}</div><button onClick={() => dispatch.sharks.increment(1)}>添加1</button><button onClick={() => dispatch.sharks.incrementAsync(3)}>异步添加3</button></div>);
}

三、rematch在Ts中的使用

  • react+hooks+ts+rematch示例代码