Redux基础使用,有备无患

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

当前计数为:{counter}

<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 (

{a}

点我用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)}/>

}

  • 21
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值