【React 框架】redux / react-redux

一、概述

1、redux 是什么?

        (1)redux 是一个专门用于做状态管理的 JS 库 ( 不是 react 插件库 )。

        (2)它可以用在 react、angular、vue等项目中, 但基本与 react 配合使用。

        (3)作用:集中式管理 react 应用中多个组件共享的状态。

学习文档:

        (1)英文文档:Redux - A predictable state container for JavaScript apps. | Redux

        (2)中文文档:Redux中文文档

        (3)github:https://github.com/reactjs/redux

2、什么情况下需要使用 redux?

        (1)某个组件的状态,需要让其他组件可以随时拿到(共享)。

        (2)一个组件需要改变另一个组件的状态(通信)。

        (3)总体原则:能不用就不用,如果不用比较吃力才考虑使用。

3、redux 工作流程

流程说明: 

        (1)React Components 是组件,用于实现某种功能,呈现某种效果。

        (2)Action Creators 在 redux 中派发 action 方法,action 通过 store 的 dispatch 方法派发给 Store。

        (3)Store 接收 action,连同之前的 previousState,一起传递给 Reducers。

        (4)Reducers 将处理后的数据返回给 Store。

        (5)Store 改变自身的 state,组件可以通过 store.getState() 方法获取到 state。

餐厅例子说明:

         (1)【React Components — 客人】、【Action Creators — 服务员】、

                  【Store — 老板】、【Reducers — 厨师】。

        (2)客人来餐厅点餐,告诉服务员具体要求(什么菜系,菜名),服务员将记录下的菜单 (action) 拿给餐厅老板,老板反手交代厨师去做菜。厨师做好菜之后,将菜拿到前台老板处,老板叫号让客人过来取。

二、案例( 基于 redux )

1、纯 react 版 

/*  components/Count/index.jsx  */

import React, { Component } from 'react'

export default class Count extends Component {

	state = { count: 0 }

	//加法
	increment = () => {
		const { value } = this.selectNumber
		const { count } = this.state
		this.setState({ count: count + value * 1 })
	}

	//减法
	decrement = () => {
		const { value } = this.selectNumber
		const { count } = this.state
		this.setState({ count: count - value * 1 })
	}

	//奇数再加
	incrementIfOdd = () => {
		const { value } = this.selectNumber
		const { count } = this.state
		if (count % 2 !== 0) {
			this.setState({ count: count + value * 1 })
		}
	}

	//异步加
	incrementAsync = () => {
		const { value } = this.selectNumber
		const { count } = this.state
		setTimeout(() => {
			this.setState({ count: count + value * 1 })
		}, 500)
	}

	render() {
		return (
			<div>
				<h1>当前求和为:{this.state.count}</h1>
				<select ref={c => this.selectNumber = c}>
					<option value="1">1</option>
					<option value="2">2</option>
					<option value="3">3</option>
				</select>&nbsp;
				<button onClick={this.increment}>+</button>&nbsp;
				<button onClick={this.decrement}>-</button>&nbsp;
				<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>&nbsp;
				<button onClick={this.incrementAsync}>异步加</button>&nbsp;
			</div>
		)
	}
}

2、redux 精简版

2.1 src 代码结构

2.2 store.js

步骤:

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值