前两天项目(Antd + Umijs)项目中传值不方便, 于是便想到了store全局状态管理
看了下文档Umijs既然内置了那就直接按照文档搞起~ 传送门 👈🏻
文档里比较详细,原理 场景 配置项 范例一应俱全.
我没有用Umi中的@connect
反而是用的Dva中的connect
,都差不多
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| const model = { namespace: "test", state: { key: 0, }, effects: { *query({ payload }, { call, put, select }) { yield call(payload.Debug);
yield put({ type: "add50", payload: { value: 50, }, });
return "成功"; }, }, reducers: { add(state, { payload }) { state.key = state.key + payload.value; }, add50(state, { payload }) { state.key = state.key + 50; }, asyncAdd(state, { payload }) { new Promise((resolve, reject) => { setTimeout(() => { state.key = state.key + 1; resolve(null); }, 2000); }); }, }, subscriptions: { setup({ dispatch, history }) { return history.listen(({ pathname }) => { console.log(`setup`);
if (pathname === "/") { dispatch({ type: "query", }); } }); }, }, }; export default model;
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import React, { useState } from "react"; import { history, useLocation } from "umi"; import { connect } from "dva";
const Store = ({ dispatch, test }) => { const addSome = () => { dispatch({ type: "test/add", payload: { value: 100, }, }); }; const addFifty = () => { dispatch({ type: "test/query", payload: { Log: Log, Debug, }, }).then((res) => { console.log(res); }); };
const Log = () => { console.log(`Log`); }; const Debug = () => { console.log(`Debug`); };
return ( <> <div> {<p>页面1key的值:{test.key}</p>} <button onClick={() => addSome()}>加上传入的Number</button> <button onClick={() => addFifty()}>固定加Number</button> </div> </> ); }; export default connect((state) => state)(Store);
|
还是补一版@connect写法
吧,这里不是函数式编程,是继承类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| import React, { useState } from "react"; import { history, useLocation } from "umi";
import { connect } from "umi";
@connect(({test})=>({ test, }))
class Store2 extends React.Component { constructor(props) { console.log(props); super(props);
}
Log = () => { console.log(`Log`); }; Debug = () => { console.log(`Debug`); };
addSome = () => { this.props.dispatch({ type: "test/add", payload: { value: 100, }, }); };
addFifty = () => { this.props.dispatch({ type: "test/query", payload: { Log: this.Log, Debug: this.Debug, }, }).then((res) => { console.log(res); }); };
render() { return ( <div onClick={() => { this.props.dispatch({ type: 'user/test', }); }} > {this.props.test.key} <button onClick={this.addFifty}>固定加Number</button> </div> ); } }
export default Store2;
|