npm i redux
在src新建store文件夹写入index.tsx 并配置代码 action会接受来自页面传过来的参数
import { createStore } from "redux"
2
let numReducer = (state = { num: 10 }, action: any) => {
console.log(action)
switch (action.type) {
case "add":
return { num: state.num + action.num }
}
return state
}
export default createStore(numReducer)
在页面使用 dispatch会触发action 数据的修改只能是通过action来进行 页面无法进行修改
引入 import store from "../store/index"
使用 {store.getState().num}
加法使用 store.dispatch({
type:"add",
num:3
})
import React, { Component } from 'react'
import store from "../store/index"
export default class About extends Component {
render() {
return (
<div>
关于{store.getState().num}
<button onClick={() => {
store.dispatch({
type: "add",
num: 3,
playload: 100
})
this.forceUpdate()
}}>加法</button>
</div>
)
}
}