- 安装 redux
# NPM
npm install redux
# Yarn
yarn add redux
- 创建redux文件
// actionTypes.js 公共变量,避免多次使用时书写错误
export const INCREMENT = 'increment'
// actions.js //为描述应用程序中发生了什么的事件.
// 同步方法
export const increment = count => ({ type: INCREMENT, data: count })
// reducers // 事件监听器,它根据接收到的 action(事件)类型处理事件。
import { combineReducers } from 'redux'// 多个方法时 用combineReducers暴露且 combineReducers 是对象
import { INCREMENT} from './actionsTypes'
const countAdd = (state = 0, action) => {
switch (action.type) {
case INCREMENT:
return state + action.data
default:
return state
}
}
const xxx = (state, action) => {}
export default combineReducers({countAdd, xxx})
// store //当前 Redux 应用的状态存在于一个名为 store 的对象中 通过 getstate 取值
import { createStore } from 'redux'
import reducers from './reducers'
// 生成一个store对象
const store = createStore(reducers) // 内部会第一次调用reduer函数得到初始state
export default store
注意
store 需要在 根目录引入
// index.js
import store from './redux/store'
ReactDOM.render(
<React.StrictMode>
<App store= {store} />
</React.StrictMode>,
document.getElementById('root')
);
// 需要用 subscribe 监听 store的变化
store.subscribe(()=>{
ReactDOM.render(
<React.StrictMode>
<App store= {store} />
</React.StrictMode>,
document.getElementById('root')
);
})
// 改写
function render() {
ReactDOM.render(<App store={store}/>, document.getElementById('root'))
}
// 初始化渲染
render()
// 订阅监听(store中的状态变化了, 就会自动调用进行重绘)
store.subscribe(render)
- 使用
// 在使用的文件 引入actions里面的方法
// 例如
import {increment} from './redux/actions'
export default class App extends Component {
increment = () => {
// 1. 得到选择增加数量
const number = this.select.value * 1
// increment调用方法传值
this.props.store.dispatch(increment(number))
}
render() {
// 通过 this.props.countAdd.getState 取state变化后的值 // countAdd是 reducers 里面暴露的方法
const {countAdd} = this.props.store.getState()
console.log(this.props.store.getState().countAdd)
return (
<button onClick={this.increment}>+</button>
)
}
}