Redux简介和使用场景
redux:一个专门做状态管理的JS库,可以集中式管理react应用中多个组件共享的状态
使用的两种情况:
(1)某个组件的状态,需要让其他组件可以随时拿到(共享)
(2)一个组件需要改变另一个组建的状态(通信)
Redux的工作流程

我理解的:
React Components提要求告诉Action Creators,然后Action Creators把type和data告诉Store,Store知道后再把东西传给Reducers,Reducers加工完把新的state返给Store。
Action Creators:核心是把获取到的东西包装成对象,也可以不要它
Reducers:不仅能够加工对象,也可以进行初始化
如果比作一家餐厅的话,React Components是顾客,Store是老板,Action Creators是服务员,Reducers是后厨团队。
Redux三个核心概念
一、action
1.动作的对象
2.包含两个属性
type:标识属性,值为字符串,必要属性
data:数据属性,值类型任意,可选属性
3.例子:{type:’ADD_STUDENT’,data:{name:’tom’,age:18}}
二、reducer
1.用于初始化状态、加工状态
2.加工时,根据旧的state和action,产生新的state的纯函数
三、store
1.将state、action、reducer联系在一起
2.如何得到此对象?
(1)import {createStore} from ‘redux’
(2)import reducer from ‘./reducers’
(3)const store = createStore(reducer)
3.此对象的功能
(1)getState():得到state
(2)dispatch(action):分发action,触发reducer调用,产生新的state
(3)subscribe(listener):注册监听,当产生了新的state时,自动调用
Redux三个API
第一个API:getState
第二个API:dispatch
组件里要执行的函数需要去通知store自己要执行,这就需要用dispatch(注意要告诉自己的type和data)
第三个API:subscribe
Redux里状态的改变不会引起页面更新,所以需要监测redux里状态的变化,而监测就需要用subscribe
Redux实际应用
App.jsx文件
1 2 3 4 5 6 7 8 9 10 11
| import React, { Component } from 'react' import Count from './Components/Count'
export default class App extends Component { render() { return ( <div><Count/></div> ) } }
|
index.js入口文件
1 2 3 4 5 6 7 8 9 10 11
| import React from "react" import ReactDOM from "react-dom" import App from "./app" import store from "./redux/store"
ReactDOM.render(<App/>,document.getElementById("root"))
store.subscribe(()=>{ ReactDOM.render(<App/>,document.getElementById("root")) }) //这样就不用在每个组件的componentDidMount() {}中都写
|
store.js文件
1 2 3 4
| //此文件专门用于暴露一个store对象 import {createStore} from 'redux' import countReducer from './countReducer' export default createStore(countReducer)
|
count_reducer.js文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const initState = 0 export default function countReducer(preState=initState, action){ const {type,data} = action switch(type){ case 'increment': return preState + data break; case 'decrement': return preState - data break; default: return preState } }
|
组件中的count.js文件
(这里隐藏着一个小问题哦……)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import React,{ Component} from 'react' import store from '../../redux/store'
export default class Count extends Component { increment=()=>{ const {value} = this.selectNumber store.dispatch({type:'increment',data:value*1}) } decrement=()=>{ const {value} = this.selectNumber store.dispatch({type:'decrement',data:value*1}) } render() { return ( <div> <h1>当前求和为:{store.getState()}</h1> <select ref={c => this.selectNumber = c}> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <button onClick={this.increment}>+</button> <button onClick={this.decrement}>-</button> </div> ) }
}
|
木有了