【React】Redux入门 & store体验
组件间传值联动是令人头疼的问题,尤其是一个组件影响多个其他组件状态变化的时候,常常需要一级一级与父组件传值,与父组件的兄弟组件传值等等,
如何化繁为简地处理‘牵一发动全身’的清理就是将所有组件的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()
)
}
}
总结
- reducer 中定义好所有组件中需要的 state 中对应的变量结构
- const store = createStore(reducer) 新建 store
- 组件构造方法中 this.state = store.getState(); 从 store 中同步初始数据
- 组件订阅 store 变化 , store.subscribe(this.handleStoreChange.bind(this));
- 组件通过方法 传递 action 给 store, store 通过 dispatch(action) 解析,让reducer 更新数据,返回新 state 给 store
原文链接:https://blog.csdn.net/Maximus_ckp/article/details/81872273
【React】Redux入门 & store体验的更多相关文章
- 看了就学会之React redux入门示例
环境准备 为了方便,这里使用create-react-app搭建react环境 create-react-app mydemo 弹出配置 如果需要自定义react的配置,需要运行下面的命令把配置文件弹 ...
- React + Redux 入门(一):抛开 React 学 Redux
http://www.hacke2.cn/think-in-react-redux-1/
- react+redux官方实例TODO从最简单的入门(6)-- 完结
通过实现了增-->删-->改-->查,对react结合redux的机制差不多已经了解,那么把剩下的功能一起完成吧 全选 1.声明状态,这个是全选状态 2.action约定 3.red ...
- react+redux官方实例TODO从最简单的入门(1)-- 前言
刚进公司的时候,一点react不会,有一个需求要改,重构页面!!!完全懵逼,一点不知道怎么办!然后就去官方文档,花了一周时间,就纯react实现了页面重构,总体来说,react还是比较简单的,由于当初 ...
- React从入门到放弃之前奏(3):Redux简介
安装 npm i -S redux react-redux redux-devtools 概念 在redux中分为3个对象:Action.Reducer.Store Action 对行为(如用户行为) ...
- React从入门到放弃之前奏(4):Redux中间件
redux 提供了类似后端 Express 的中间件概念. 最适合扩展的是redux中的 store.dispatch 方法,中间件实际就是通过 override redux的store.dispat ...
- 6周学习计划,攻克JavaScript难关(React/Redux/ES6 etc.)
作者:余博伦链接:https://zhuanlan.zhihu.com/p/23412169来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 和大家一样,最近我也看了Jo ...
- React Redux Sever Rendering实战
# React Redux Sever Rendering(Isomorphic JavaScript)  Python基础之函数2 (参数的 ...
- Python之Beautiful Soup 4使用实例
Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库,它能够通过你喜欢的转换器实现惯用的文档导航.查找.修改文档的方式.Beautiful Soup 4 官方文档: ...
- Web服务器—Nginx
Nginx常用命令: 启动nginx服务 [root@localhost ~]# service nginx start [root@localhost ~]# systemctl start ngi ...
- Rust,重温猜猜看
其实,这个知识点蛮多的, 常看常新. use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Gu ...
- 电商网站名词item-->SKU与SPU
一.总述: item sku spuitem 代表一种商品,是和店铺关联的.sku 商品的库存量单位 , 代表商品的规格和属性spu 产品单位最小分割的商品 ,与商家无关 它的属性会影响价格. 简单的 ...
- day51_9_15_Django
一.pycharm接受网页信息原理. 如何实现在后端接受浏览器的数据,并解析出有用的信息呢? 使用socket编写网络连接,然后通过浏览器访问ip+端口号. import socket def ind ...
- CF1010D Mars rover
CF1010D Mars rover 洛谷评测传送门 题目描述 Natasha travels around Mars in the Mars rover. But suddenly it broke ...
- web 服务
package main import ( "strings" "fmt" "net/http" "log" ) fun ...
- 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.ClassNotFoundException in matlabR2014a 就是MATLAB和pycharm不能同时运行.关闭pycharm然后打开MATLAB就可以了.
- Paper | Fast image processing with fully-convolutional networks
目录 故事 方法 实验 发表在2017年ICCV. 核心任务:加速图像处理算子(accelerate image processing operators). 核心方法:将算子处理前.后的图像,训练一 ...