React项目中redux使用

一、复杂项目使用步骤

1、安装

yarn add redux react-redux

2、新建 reducer/index.ts 文件
// 初始化值
const initState = {
    status: false
}

export.myReducer = (state = initState, action) => {
    switch (action.type) {
        case 'SEND':
            return { status: true }
        default:
            return state
    }
}
3、新建 store/index.ts 文件
import {createStore } from 'redux'
import { myReducer } from '../reducer'

export default createStore(myReducer)
4、根文件 app.ts 导入 Provider
import store from '../store'
import { Provider } from 'react-redux'

function App(){
    return(
        <Provider storr={store}>
        // ...
        </Provider>
    )
}
export default App
5、发送的组件使用

通过 this.props 获取对应的触发 action 函数

import { Component } from 'react'
import { connect } from 'react-redux'

class A extends Component {
    render() {
        console.log('A:', this.props.send)
        return (
            <>
            // ...
            </>
        )
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        send: () => {
            dispatch({ type: 'SEND' })
        },
    }
}

export default connect(null, mapDispatchToProps)(A)
6、接收的组件使用

通过 this.props 获取传的 key 的 value 值

import { Component } from 'react'
import { connect } from 'react-redux'

class B extends Component {
    render() {
        console.log('B:', this.props.status)
        return (
            <>
            // ...
            </>
        )
    }
}

const mapStateToProps = (state) => {
    return state
}

export default connect(mapStateToProps)(B)

二、单个某属性使用案列

1、创建store
  • reducer
  • appStore 创建store
  • dispatch 更新
// 引入
import { createStore, Reducer, combineReducers } from 'redux'

export interface AppState {
    todoCount?: number
    toPayCount?: number
}

type AppStateAction = {
    type: "refresh",
    todoCount?: number
    toPayCount?: number
}

const reducer: Reducer<AppState, AppStateAction> = function (state: AppState | undefined, action: AppStateAction) {
    switch (action.type) {
        case 'refresh':
            return {
                todoCount: action.todoCount ?? state?.todoCount,
                toPayCount: action.toPayCount ?? state?.toPayCount
            }
        default:
            return state ?? {};
    }
};

export const appStore = createStore(combineReducers({ appStatus: reducer }))


export class AppActions {
    static refreshTodoNumber() {
        api.bank.processQueryTodoNum(autoToken({}), { businessCheck: false, showLoading: false }).then((res, {isOk}) => {
            if (isOk) {
                appStore.dispatch({
                    type: 'refresh',
                    todoCount: res?.data?.toApprove,
                    toPayCount: res.data?.toPay
                })
            }
        }).catch(e => {
            console.log(e)
        })
    }

    static todoApproved(todo?: ApproveVo) {
        this.refreshTodoNumber();
    }

    static todoRejected(todo?: ApproveVo) {
        this.refreshTodoNumber();
    }
}
2、其他文件使用store
import { connect } from 'react-redux'

// 更新action 
// 触发action更新reducer,进而更新state
const mapDispatchToProps = (dispatch: Function) => {

    return {
        postRefresh: () => {
            AppActions.refreshTodoNumber();
        }
    }
}

// 更新props,返回一个对象
// key为对应的字段,value为state对应的值
const mapStateToProps = (state: any) => {
    return {
        todoCount: state.appStatus?.todoCount,
        toPayCount: state.appStatus?.toPayCount
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MainPage)
3、Provider
  • 使App的所有子组件都可以获取到 state
  • 引入之前导出的 appStore
import { Provider } from 'react-redux'
import { appStore } from '@mds/app-core';
<Provider store={appStore}>
    <App />
</Provider>

官方参考文档

你可能感兴趣的:(React,TypeScript,前端开发,react.js,javascript,前端)