react项目中使用redux的简单案例

1. 在react-cli项目中安装redux

npm -i redux --save

2. 创建store文件夹

// src/store/reducers.js

const initState = {
    
    
    num: 0,
}

function reducer(state = initState, action) {
    
    
    console.log("reducer", state, action)
    switch (action.type) {
    
    
        case "ADD_NUMBER":
        	// reducer返回值就是更新后的state的值
            return {
    
    
                num: state.num + action.num,
            }
        case "SUB_NUMBER":
            return {
    
    
                num: state.num - action.num,
            }
        default:
            return state
    }
}
export default reducer
// src/store/index.js

import {
    
     createStore } from 'redux'
import reducer from "./reducers.js";

export default createStore(reducer)
// src/store/actions.js 

// 加
export const addAction = (num) => {
    
    
    return {
    
    
        type: "ADD_NUMBER",
        num: num * 2,
    }
}

// 减
export const subAction = (num) => ({
    
    
    type: "SUB_NUMBER",
    num,
})

3. 组件中使用

import React, {
    
     useEffect } from "react"
import store from "../../store"
import {
    
     subAction, addAction } from "../../store/actions"
// console.log('store', store)

class StoreDemo extends React.Component {
    
    
    toAdd() {
    
    
        console.log("add")
        // store.dispatch({
    
    
        //     type: "ADD_NUMBER",
        //     num: 4,
        // })
        store.dispatch(addAction(2))
    }
    toSub() {
    
    
        console.log("sub -2")
        store.dispatch(subAction(2))
    }

    componentDidMount() {
    
    
    	// 监听中store的更新
        store.subscribe(() => {
    
    
            console.log("监听中store", store.getState())
            // 更新视图
            this.setState({
    
    })
        })
    }

    render() {
    
    
        return (
            <>
                <button className={
    
    "ma10"} onClick={
    
    () => this.toSub()}>
                    -
                </button>
                {
    
    store.getState().num}
                <button className={
    
    "ma10"} onClick={
    
    () => this.toAdd()}>
                    {
    
    " "}
                    +{
    
    " "}
                </button>
            </>
        )
    }
}

export default StoreDemo

效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44801790/article/details/126382762