含义
Redux是专门用作状态管理的js库,不是react插件库 可以用在react、angular、vue等项目中 能集中式管理react应用中多个组件共享的状态
使用
npx create- react- app redux1
cnpm install redux - S
关键字
store reducer action subscribe
案例
1. 创建store、并传入reducer
import { createStore } from 'redux'
import { counter } from './redux/reducers'
const store = createStore ( counter)
2. 使用dispatch
store. dispatch ( {
type : '' ,
data: '' ,
} )
3. reducer里处理数据
function counter ( state = 0 , action) {
const { type , data } = action
}
4. 监听state,触发更新
store. getState ( )
store. subscribe ( render)
import ReactDOM from 'react-dom'
import App from './App'
import { createStore } from 'redux'
import { counter } from './redux/reducers'
const store = createStore ( counter)
store. subscribe ( render)
function render ( ) {
ReactDOM. render (
< App store= { store} / > ,
document. getElementById ( 'root' )
)
}
render ( )
export function counter ( state = 0 , action) {
const { type , data } = action
console . log ( 'reduce 触发了方法' , type )
console . log ( 'reduce 接收参数' , data)
switch ( type ) {
case 'add' :
return state + data
case 'minus' :
return state - data
case 'add_odd' :
if ( data % 2 !== 0 ) {
return state + data
}
case 'add_delay' :
setTimeout ( ( ) => {
return state + data
} , 1000 )
default :
return state
}
}
export function add ( param) {
return {
type : 'add' ,
data: param
}
}
export function minus ( param) {
return {
type : 'minus' ,
data: param
}
}
export function add_odd ( param) {
return {
type : 'add_odd' ,
data: param
}
}
export function add_delay ( param) {
return {
type : 'add_delay' ,
data: param
}
}
import React, { Component, createRef } from 'react'
import * as actions from './redux/action'
export default class App extends Component {
constructor ( props) {
super ( props)
this . selectRef = createRef ( )
}
compute = ( method) => {
const selectDom = this . selectRef. current,
selectVal = Number ( selectDom. value) ,
store = this . props. store;
console . log ( 'app store/method' , store, method)
store. dispatch ( actions[ method] ( selectVal) )
}
render ( ) {
const count = this . props. store. getState ( )
console . log ( '重新render了' , count)
return (
< >
< h1> 数值:{ count} < / h1>
< select ref= { this . selectRef} >
< option value= "1" > 1 < / option>
< option value= "2" > 2 < / option>
< option value= "3" > 3 < / option>
< / select> & nbsp;
< button onClick= { ( ) => this . compute ( 'add' ) } > + < / button> & nbsp;
< button onClick= { ( ) => this . compute ( 'minus' ) } > - < / button> & nbsp;
< button onClick= { ( ) => this . compute ( 'add_odd' ) } > 奇数加< / button> & nbsp;
< button onClick= { ( ) => this . compute ( 'add_delay' ) } > 延迟加< / button>
< / >
)
}
}