啥都不說族淮,先上傳送門:github地址
margaret
? margaret是react的下一代路由庫,基于社區(qū)反映react 的router痛點進行了新的設計七芭,本庫有2種模式胯府,第一種是不保存路由狀態(tài)的路由系統(tǒng)中姜,與react-router一致,第二種是能夠持久保持路由狀態(tài)的荔燎,react路由庫,可用于開發(fā)在切換頁面后销钝,再次切換回來時有咨,打開頁面依然保持之前操作過的狀態(tài)。
? 同時利用react hook打造了一款數據流處理庫蒸健,用法與redux思路一致座享,但更為簡化
? margaret是一款極為輕量的庫婉商,api也極少,數據流是基于hook的context特性進行開發(fā)渣叛,2種路由方式無縫切換丈秩,用戶的項目保持不變
用法
安裝:
npm install margaret
or
yarn add margaret
必要的配置:
- 必須在react入口處配置Provider
import {MgProvider} from "margaret";
import * as reducer from "./reducer";
//reducer就是用戶自己定義的reducer文件
<MgProvider reducer={reducer}>
<App/>
</MgProvider>
- 自定義reducer文件reducer.js的編寫
export const count1 = (state = 1, action={}) => {
switch (action.type) {
case "ADD":
return state + 1;
case "JIAN":
return state - 1;
default:
return state;
}
}
export const count2 = (state = 3, action={}) => {
switch (action.type) {
case "ADD2":
return state + 2;
case "JIAN2":
return state - 2;
default:
return state;
}
}
- router文件的編寫
let baseRoutes = [{
name: "home",
path: "/",
hide: true,
component: Home,
}, {
name: "page1",
path: "/page1",
component: Page1,
}, {
name: "page2",
path: "/page2",
component: Page2,
},{
name: "page5",
path: "/page5",
redirect:"/page5/page3",
children: [{
name: "page3",
path: "/page3",
component: Page3,
}]
}]
export default function Index(prop) {
const {dispatch, mgRouter} = mg()
return (
<KeepRouter data={baseRoutes}/>
)
}
- 界面的調用
import React, {Fragment, useEffect, useState, useContext} from 'react';
import Page1 from "@page/page1"
import Page2 from "@page/page2"
import Page3 from "@page/page3"
import {history, Link,mg,Router} from "margaret"
export default function Index(prop) {
const {count1, count2,dispatch, setKeepRouterData} = mg()
const goTo = (url) => {
history.push(url)
}
return (
<Fragment>
{count1}
<button onClick={() => {
dispatch({
type: "ADD"
})
}}>add
</button>
<button onClick={() => {
dispatch({
type: "JIAN"
})
}}>subtraction
</button>
<br/>
{count2}
<button onClick={() => {
dispatch({
type: "ADD2"
})
}}>add1
</button>
<button onClick={() => {
dispatch({
type: "JIAN2"
})
}}>subtraction2
</button>
<br/>
<Link to="/page5">link to page 5</Link>
<a onClick={() => goTo("/page1")}>page1</a>
<a onClick={() => goTo("/page2")}>page2</a>
<a onClick={() => goTo("/page5/page3", {state: 11})}>page3</a>
</Fragment>
);
}
里面包含了數據流的使用以及路由的使用,如果只是想用數據流則不引入router即可淳衙,在需要用的頁面中用mg接收數據及dispatch函數蘑秽,詳細文檔請看:地址
License
margaret is MIT licensed.