react 结合 redux
redux 融入 react 代码
JSX
JSX
import React, { PureComponent } from "react";
import store from "./store/index.js";
import { addAction } from "./store/actionCreators.js";
export default class Home extends PureComponent {
constructor(props) {
super(props);
this.state = {
counter: store.getState().counter,
};
}
componentDidMount() {
store.subscribe(() => {
this.setState({ counter: store.getState().counter });
});
}
render() {
return (
<div>
<h1>Home</h1>
<h2>当前计数: {this.state.counter}</h2>
<button onClick={(e) => this.increment()}>+1</button>
<button onClick={(e) => this.addCounter()}>+5</button>
</div>
);
}
increment() {
store.dispatch(addAction(1));
}
addCounter() {
store.dispatch(addAction(5));
}
}
import React, { PureComponent } from "react";
import store from "./store/index.js";
import { subAction } from "./store/actionCreators.js";
export default class Profile extends PureComponent {
constructor(props) {
super(props);
this.state = {
counter: store.getState().counter,
};
}
componentDidMount() {
store.subscribe(() => {
this.setState({ counter: store.getState().counter });
});
}
render() {
return (
<div>
<hr />
<h1>Profile</h1>
<div>
<h2>当前计数: {this.state.counter}</h2>
<button onClick={(e) => this.decrement()}>-1</button>
<button onClick={(e) => this.subCounter()}>-5</button>
</div>
</div>
);
}
decrement() {
store.dispatch(subAction(1));
}
subCounter() {
store.dispatch(subAction(5));
}
}
自定义 connect 函数
-
上面的代码会发现每个使用的地方其实会有一些重复的代码:
- 比如监听 store 数据改变的代码,都需要在 componentDidMount 中完成;
- 比如派发事件,都需要去先拿到 store, 在调用其 dispatch 等;
-
定义一个 connect 函数,将这些公共的内容提取出来:
- 参数:
- 参数一:里面存放 component 希望使用到的 State 属性;
- 参数二:里面存放 component 希望使用到的 dispatch 动作;
- 返回值,是一个高阶组件:
- 在 constructor 中的 state 中保存一下需要获取的状态;
- 在 componentDidMount 中订阅 store 中数据的变化,并且执行 setState 操作;
- 在 componentWillUnmount 中需要取消订阅;
- 在 render 函数中返回传入的 WrappedComponent,并且将所有的状态映射到其 props 中;
- 这个高阶组件接受一个组件作为参数,返回一个 class 组件;
- 参数:
-
实例代码:
JSX
JSX
JSX
// src/connect.js
import React, { PureComponent } from "react";
import store from "../store";
export default function connect(mapStateToProps, mapDispatchToProps) {
return function handleMapCpn(WrappedComponent) {
return class extends PureComponent {
constructor(props) {
super(props);
this.state = {
storeState: mapStateToProps(store.getState()),
};
}
componentDidMount() {
this.unsubscribe = store.subscribe(() => {
this.setState({
storeState: mapStateToProps(store.getState()),
});
});
}
componentWillUnmount() {
this.unsubscribe();
}
render() {
return (
<WrappedComponent
{...this.props}
{...mapStateToProps(store.getState())}
{...mapDispatchToProps(store.dispatch)}
/>
);
}
};
};
}
store 的 context 处理
react-redux 使用
打赏作者
您的打赏是我前进的动力
微信
支付宝
Redux✍️ Redux 初见
上一篇
评论