一、需要安装的模块(代码不多,都是经典,看完就会用)
1.安装需要的redux模块(redux、 react-redux、 redux-thunk)
npm i redux react-redux redux-thunk --save
- 安装redux的调试工具
npm i redux-devtools-extension
二、开始使用redux,仔细观察文件目录,没有的就自己创建
1. /src/redux/store.js
//用于创建store
import { applyMiddleware, createStore } from "redux"
import allReducer from "./reducers"//将多个reducer合并为一个
import thunk from "redux-thunk" //引入异步模块
import {composeWithDevTools} from "redux-devtools-extension"
export default createStore(allReducer, composeWithDevTools(applyMiddleware(thunk)))//创建并导出store对象
2. /src/redux/constants.js
// 编写常量类型字典
export const INCREAMENT = "increament" //增加的类型常量
export const DECREAMENT = "decreament" //减少的类型常量
export const UNSHIFTLIST = "unshiftList" //在list数组的前边新增数据
3. /src/redux/reducers/count.js
import { INCREAMENT, DECREAMENT} from "../constants"
export default function setCount(pre= 1, action) {//第一个参数是初始化仓库状态的初始值,第二个参数是action对象
const {type, data} = action
switch (type) {
case INCREAMENT:
return pre + data
case DECREAMENT:
return pre - data
default:
return pre
}
}
4. src/redux/reducers/list.js
import { UNSHIFTLIST} from "../constants"
export default function setList(pre=[], action) {
const {type, data} = action
switch (type) {
case UNSHIFTLIST:
return [data, ...pre]
default:
return pre
}
}
5. /src/redux/reducers/index.js
import {combineReducers} from "redux"//combineReducers用于将多个reducer进行合并为一个reducer
import count from "./count"
import list from "./list"
export default combineReducers({
count,
list,
})
6. /src/redux/actions/count.js
import {INCREAMENT, DECREAMENT} from "../constants"
// 创建一个同步action
export const increament = data => ({type: INCREAMENT, data})
export const decreament = data => ({type: DECREAMENT, data})
// 创建一个异步action
export const increamentAsync = data => {
return (dispatch) => {
// 异步任务在此执行
setTimeout(()=> {
dispatch(increament(data))
}, 1000)
}
}
三、使用redux进行取值与修改仓库的值
在/src/Home/Home.jsx中,进行读取仓库中的值
import {connect} from "react-redux" //connect是一个高阶函数,用于包装一个组件,返回一个新的组件
import {increament, decreament } from "../../redux/actions/count"
class Home extends Component {
increament =() => {
this.props.increament(10)
}
decreament =() => {
this.props.decreament(10)
}
render() {
return (
<div>
我是HOME组件,仓库中的count值为{this.props.count}
<button onClick={this.increament}>HOMEincreament</button>
<button onClick={this.decreament}>HOMEdecreament</button>
</div>
)
}
}
export default connect(
state=>({count: state.count}),//connect第一个参数是一个形参为仓库state状态的函数,
{
increament,//第二个参数为一个对象
decreament
}
)(Home)