组件间传值联动是令人头疼的问题,尤其是一个组件影响多个其他组件状态变化的时候,常常需要一级一级与父组件传值,与父组件的兄弟组件传值等等,

如何化繁为简地处理‘牵一发动全身’的清理就是将所有组件的state中的值,用redux数据框架store统一记录管理。

ReactComponents(组件)通过ActionCreators告诉Store要获取/更改哪个值,Store通过查询Reducer后,更新Reducer的值再将更新后的值传递给ReactCompnents

保持组件与Store中的存储数据的同步。可以理解为ReactCompents为借书的人,ActionCreators为借书人说出的借书请求,Store为图书管理员,Reducer是记录书籍的小本本儿

使用步骤:

1.安装Redux

npm install --save redux

2.src下新建 store 文件夹,并新建index.js

3.index.js中 通过 createStore 方法创建 store

import { createStore } from 'redux';

const store =createStore();

export default store;

4.store 文件夹下新建 reducer.js 并声明各组件所需 state 中的变量

const defaultState = {
inputValue: '',
list:[1,2],
showMsg:false
}
export default (state = defaultState,action)=>{
return state;
}

5.将 reducer 作为参数传给 createStore 方法,创建 store

import { createStore } from 'redux';
import reducer from './reducer'; const store =createStore(reducer); export default store; 

6.将组件文件中引入 store 并将 state 与 store 进行绑定

// 引入store
import store from './store'; // './store/index.js'的简写
...
class Todolist extends Component {
constructor(props){
super(props);
// 原组件中的state与store进行绑定
// this.state={
// inputValue: '', // 输入框中的值
// list: [], // todolist数组
// showMsg: false
// }
this.state = store.getState();
...
}
...
}

7.方法中声明 action 传递给 store,让 store 去根据 action.type 在 reducer 中做判断,决定将 reducer 中哪个值改为 action.value,并返回一个新 state 让 store 通知组件去更新

<input type="text" value={this.state.inputValue} onChange={this.handleInput}/>

  

// 动态监听输入变化inputValue值
handleInput(e) {
// let inputValue = e.target.value; // 获取input值
// this.setState({
// inputValue // 键值对相同时 可简写
// });
const action = {
type:'change_input_value',
value:e.target.value
}
store.dispatch(action); // 解析action
}

 reducer.js 中接收 action,返回最新数据给 store

const defaultState = {
inputValue: '',
list:[1,2],
showMsg:false
}
export default (state = defaultState,action)=>{
// 根绝action.type 判断更改何值
if(action.type === 'change_input_value'){
// why copy old state -> newState ? reducer 可以接收state 不能修改state!!!
const newState = JSON.parse(JSON.stringify(state)); // 深度拷贝
newState.inputValue = action.value;
return newState;
}
return state;
}

8.store 的变化要与组件联动,组件需要注册监听 store 的变化,并通过回调更新组件的state

 

// 引入store
import store from './store'; // './store/index.js'的简写
...
class Todolist extends Component {
constructor(props){
super(props);
this.state = store.getState();
// 注意需要绑定 this
this.handleStoreChange = this.handleStoreChange.bind(this);
// 注册监听store,store变化后调用组件的handleStoreChange方法更新组件的state
store.subscribe(this.handleStoreChange);
...
}
...
// store 变化后,更新组件的 state
handleStoreChange() {
this.setState(
store.getState()
)
}
}  

总结

  1. reducer 中定义好所有组件中需要的 state 中对应的变量结构
  2. const store = createStore(reducer) 新建 store
  3. 组件构造方法中 this.state = store.getState(); 从 store 中同步初始数据
  4. 组件订阅 store 变化 , store.subscribe(this.handleStoreChange.bind(this));
  5. 组件通过方法 传递 action 给 store, store 通过 dispatch(action) 解析,让reducer 更新数据,返回新 state 给 store

原文链接:https://blog.csdn.net/Maximus_ckp/article/details/81872273

【React】Redux入门 & store体验的更多相关文章

  1. 看了就学会之React redux入门示例

    环境准备 为了方便,这里使用create-react-app搭建react环境 create-react-app mydemo 弹出配置 如果需要自定义react的配置,需要运行下面的命令把配置文件弹 ...

  2. React + Redux 入门(一):抛开 React 学 Redux

    http://www.hacke2.cn/think-in-react-redux-1/

  3. react+redux官方实例TODO从最简单的入门(6)-- 完结

    通过实现了增-->删-->改-->查,对react结合redux的机制差不多已经了解,那么把剩下的功能一起完成吧 全选 1.声明状态,这个是全选状态 2.action约定 3.red ...

  4. react+redux官方实例TODO从最简单的入门(1)-- 前言

    刚进公司的时候,一点react不会,有一个需求要改,重构页面!!!完全懵逼,一点不知道怎么办!然后就去官方文档,花了一周时间,就纯react实现了页面重构,总体来说,react还是比较简单的,由于当初 ...

  5. React从入门到放弃之前奏(3):Redux简介

    安装 npm i -S redux react-redux redux-devtools 概念 在redux中分为3个对象:Action.Reducer.Store Action 对行为(如用户行为) ...

  6. React从入门到放弃之前奏(4):Redux中间件

    redux 提供了类似后端 Express 的中间件概念. 最适合扩展的是redux中的 store.dispatch 方法,中间件实际就是通过 override redux的store.dispat ...

  7. 6周学习计划,攻克JavaScript难关(React/Redux/ES6 etc.)

    作者:余博伦链接:https://zhuanlan.zhihu.com/p/23412169来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 和大家一样,最近我也看了Jo ...

  8. React Redux Sever Rendering实战

    # React Redux Sever Rendering(Isomorphic JavaScript) ![React Redux Sever Rendering(Isomorphic)入门](ht ...

  9. React+Redux实现追书神器网页版

    引言 由于现在做的react-native项目没有使用到redux等框架,写了一段时间想深入学习react,有个想法想做个demo练手下,那时候其实还没想好要做哪一个类型的,也看了些动漫的,小说阅读, ...

随机推荐

  1. 2019年上半年收集到的人工智能Python编程干货文章

    2019年上半年收集到的人工智能Python编程干货文章 一文了解Python深拷贝与浅拷贝问题 Python广度优先查找和深度优先查找(内附python教程分享) Python基础之函数2 (参数的 ...

  2. Python之Beautiful Soup 4使用实例

    Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,它能够通过你喜欢的转换器实现惯用的文档导航.查找.修改文档的方式.Beautiful Soup 4 官方文档: ...

  3. Web服务器—Nginx

    Nginx常用命令: 启动nginx服务 [root@localhost ~]# service nginx start [root@localhost ~]# systemctl start ngi ...

  4. Rust,重温猜猜看

    其实,这个知识点蛮多的, 常看常新. use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Gu ...

  5. 电商网站名词item-->SKU与SPU

    一.总述: item sku spuitem 代表一种商品,是和店铺关联的.sku 商品的库存量单位 , 代表商品的规格和属性spu 产品单位最小分割的商品 ,与商家无关 它的属性会影响价格. 简单的 ...

  6. day51_9_15_Django

    一.pycharm接受网页信息原理. 如何实现在后端接受浏览器的数据,并解析出有用的信息呢? 使用socket编写网络连接,然后通过浏览器访问ip+端口号. import socket def ind ...

  7. CF1010D Mars rover

    CF1010D Mars rover 洛谷评测传送门 题目描述 Natasha travels around Mars in the Mars rover. But suddenly it broke ...

  8. web 服务

    package main import ( "strings" "fmt" "net/http" "log" ) fun ...

  9. Exception "java.lang.ClassNotFoundException: com/intellij/codeInsight/editorActions/FoldingData"while constructing DataFlavor for: application/x-java-jvm-local-objectref; class=com.intellij.codeInsigh

    java.lang.​ClassNotFo​undExcepti​on in matlabR2014a 就是MATLAB和pycharm不能同时运行.关闭pycharm然后打开MATLAB就可以了.

  10. Paper | Fast image processing with fully-convolutional networks

    目录 故事 方法 实验 发表在2017年ICCV. 核心任务:加速图像处理算子(accelerate image processing operators). 核心方法:将算子处理前.后的图像,训练一 ...