redux教程2024

1.安装redux

yarn add redux /npm i redux

2.创建目录

action/reducer/store

3.编写action

const sendAction=()=>{
    return {
        type:'send_type',
        value:'i am action'
    }
}
module.exports={
    sendAction
}

4.编写reducer

const initState={
    value:'init'
}
const reducer=(state=initState,action)=>{
    console.log(state,action)
    switch (action.type){
        case "send_type":
            return Object.assign({},state,action)
        default:
            return state
    }
}
module.exports={
    reducer
}

5.编写store,reducer与store关联

import {createStore} from "redux";
import {reducer} from '../reducer'
const store=createStore(reducer)
export default store

6.测试store


import React from "react";
import store from "../../store";
import {sendAction} from '../../action'
export default class Home extends React.Component{

    handClick=()=>{
        const action=sendAction()
        store.dispatch(action)
    }

    componentDidMount() {
        store.subscribe(()=>{
            console.log("subscribe:",store.getState())
            this.setState({})
        })
    }

    render() {
        return (
            <>
                <button onClick={this.handClick}>点我</button>
                <div>{store.getState().value}</div>

            </>
            )
    }
}

阿芯爱编程
0 声望1 粉丝

php ,java,nodejs