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>
</>
)
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。