動態

詳情 返回 返回

redux教程2024 - 動態 詳情

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>

            </>
            )
    }
}

Add a new 評論

Some HTML is okay.