React中使用Redux
开始之前需要强调一下,redux和react没有直接的关系,你完全可以在React, Angular, Ember, jQuery, or vanilla JavaScript中使用Redux。
这里我创建了两个组件:
首先将结构搭建出来, 然后安装redux库: npm i redux
安装完成后, 安装我们上一篇文章讲解的目录结构, 创建Store文件夹
import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(reducer)
export default store
export const CHANGE_NUM = "change_num"
import { CHANGE_NUM } from "./constants"
const initialState = {
counter: 10
}
export default function reducer(state = initialState, action) {
switch(action.type) {
case CHANGE_NUM:
return {...state, counter: state.counter + action.num}
default:
return state
}
}
import { CHANGE_NUM } from "./constants"
export const changeNumAction = (num) => ({
type: CHANGE_NUM,
num
})
store中编写完成后, 在Home和Profile页面中使用store中的state, 核心代码主要是两个:
- Home组件
import React, { PureComponent } from 'react'
import store from '../store'
import { changeNumAction } from '../store/actionCreators'
export class Home extends PureComponent {
constructor() {
super()
this.state = {
counter: store.getState().counter
}
}
// 核心一: 在componentDidMount中监听store的变化,当数据发生变化时重新设置 counter;
componentDidMount() {
store.subscribe(() => {
const state = store.getState()
this.setState({ counter: state.counter })
})
}
// 核心二: 在发生点击事件时,调用store的dispatch来派发对应的action;
changeNum(num) {
store.dispatch(changeNumAction(num))
}
render() {
const { counter } = this.state
return (
<div>
<h2>Home</h2>
<h2>当前计数: {counter} </h2>
<button onClick={() => this.changeNum(1)}>+1</button>
<button onClick={() => this.changeNum(5)}>+5</button>
</div>
)
}
}
export default Home
- Profile组件
import React, { PureComponent } from 'react'
import store from '../store'
import { changeNumAction } from '../store/actionCreators'
export class Profile extends PureComponent {
constructor() {
super()
this.state = {
counter: store.getState().counter
}
}
componentDidMount() {
store.subscribe(() => {
const state = store.getState()
this.setState({ counter: state.counter })
})
}
changeNum(num) {
store.dispatch(changeNumAction(num))
}
render() {
const { counter } = this.state
return (
<div>
<h2>Profile</h2>
<h2>当前计数: {counter}</h2>
<button onClick={() => this.changeNum(-1)}>-1</button>
<button onClick={() => this.changeNum(-5)}>-5</button>
</div>
)
}
}
export default Profile
我们发现Home组件和Profile组件中的代码是大同小异的, 所以这不是我们最终编写的代码, 后面还会对代码进行优化