import { INCREMENT } from “./CONSTANT”;
const addAction = (counter:any) => {
return {
type: INCREMENT,
counter: counter,
};
};
export { addAction };
reducer.ts
import { INCREMENT } from “./CONSTANT”;
const initialState = {
counter: 20,
};
function reducer(state = initialState, action: any) {
switch (action.type) {
case INCREMENT:
return { …state, counter: state.counter + action.counter };
default:
return state;
}
}
export default reducer;
constants.ts
export const INCREMENT = ‘increment’
在组件里使用
//类组件
import React, { PureComponent } from ‘react’
import store from ‘./store’
import { addAction } from ‘./store/actionCreators’
export default class Test extends PureComponent {
state = {
counter: store.getState().counter
}
componentDidMount() {
store.subscribe(() => {
this.setState({
counter: store.getState().counter
})
})
}
render() {
const { counter } = this.state;
return (
Test
<button onClick={() => { this.increment() }}>+1
<button onClick={() => { this.addCounter() }}>+5
)
}
increment = () => {
store.dispatch(addAction(1))
}
addCounter = () => {
store.dispatch(addAction(5))
}
}
//函数组件
import React, { memo } from ‘react’;
import { useState } from ‘react’
import store from ‘…/store’
import { addAction } from ‘…/store/actionCreators’
export default memo(function Demo1() {
const initCounter = store.getState().counter;
const [a, setA] = useState(initCounter);
const add = () => {
store.dispatch(addAction(1));
setA(store.getState().counter)
}
return (
点我用reducer派发action
)
})
2.手写connect
解决监听store数据改变的代码,都需要在 componentDidMount
中完成;
解决派发事件,我们都需要去先拿到 store
, 在调用其 dispatch
等;
接受两个参数:
-
参数一:里面存放
component
希望使用到的State
属性; -
参数二:里面存放
component
希望使用到的dispatch
动作;
有一个返回值、是一个高阶组件:
-
在
constructor
中的state中保存一下我们需要获取的状态; -
在
componentDidMount
中订阅store中数据的变化,并且执行setState
操作; -
在
componentWillUnmount
中需要取消订阅; -
在
render
函数中返回传入的WrappedComponent
,并且将所有的状态映射到其props
中; -
这个高阶组件接受一个组件作为参数,返回一个class组件:
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)}/>
}