[注: 此写法不涉及分组件]
[注: 这是给自己写来看的]
本质(原理):
全局对象, 以单向数据流传递
多个组件要共享一个数据
大致工序:
component =>actionCreator -->store =>reducer =(newState)=> store=>component
状态管理工具:
早期: flux 后来的: mobx
网址: redux.org.cn
安装: NPM i redux --save
概念:
数据 state
动作 action(是一个对象, 决定对数据进行什么操作)
* 纯函数 reducer 改变 state
(纯函数: 返回值由参数决定, 参数不能改变, 不能调用 io, 调用随机数, 日期时间类函数)
* 三大原则:
1, 单一数据源 :store 只有一个
2,state 是只读的
3, 使用纯函数 (reducer) 来执行修改 state
(流程也是单向数据流)
操作:(对 a 进行 + 1)
存数据(与 + 1):
1,src 目录下新建一个 store 目录, 创一个 index.JS 文件, 一个 reducer.JS 文件
2,index 引入 :
- import {
- createStore
- } from 'redux'
- import {
- reducer
- } from './reducer'
- let store = createStore(reducer)
- export default store
3, reducer 写入:
? 注意 :state = 初始值 ,state 是修改数据的当前状态
? action 是动作 , 是一个对象, 必须有 type 属性, 必须返回状态
- //store 的初始值
- let initState = {
- a : 5
- }
- export const reducer = (state = initState ,action) =>{
- //state = store 的初始值, action 是动作 是一个对象 必须有的属性是 type
- // 下面是写 action 动作, 但是在写之前需要备份 store, 所以涉及到浅拷贝:
- let newState = {...state}
- // 或者
- let newState = Object.assign({},state)
- switch(action.type){
- case 'typeName':
- // 这里写你要做的操作, 比如:
- newState =newState.a + 1
- return newState
- default:
- return state
- }
- }
取数据:
1, 组件下新建 例: 创建了 test 文件夹, index.JS 和 actionCreator.JS
2,actionCreator 里写入:
- export default {
- testAction(n){
- return{
- type:'typeName',// 和 reducer 里的一直
- n // 传的值
- }
- }
- }
2,test.index 写入:
注: store.getState. 变量 获取初始值
store.subscribe(this. 方法名. bind(this)) 当数据变化时进行 里面的方法, 下列就是重新赋予一次值
store.dispatch(actionCreator.testAction()) 修改数据抛发动作, 其 () 内的与引入的 actionCreator 内容一致
- import React, { Component } from 'react';
- import store from './store 的文件夹'
- import actionCreator from './actionCreator';
- export default class index extends Component {
- constructor(){
- super()
- this.state={
- a : store.getState().a
- }
- // this.add = this.add.bind(this)
- store.subscribe(this.sub.bind(this))
- }
- sub(){
- this.setState({
- a : store.getState().a
- })
- }
- add(){
- store.dispatch(actionCreator.testAction())
- }
- render() {
- return (
- <div>
- {this.state.a}
- <button onClick={this.add}>+1</button>
- </div>
- )
- }
- }
[注意] testAction() 里是向 actionCreator 里传值 . 例:
- const initialState = {
- a:5
- }
- export const reducer = (state = initialState, action) => {
- let newState = {...state}
- switch (action.type) {
- case 'typeName':
- // 这里传入了 action.n 与 actionCreator 文件里的 n 对应
- newState.a = newState.a + action.n
- return newState
- default:
- return state
- }
- }
[注: reducer 是可以分组件集中管理的, 也就是组件内可以有自己的 reducer ]
未完......
来源: http://www.bubuko.com/infodetail-3164911.html