Redux 学习(二)

126 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第12天,点击查看活动详情

前言

之前学习了 redux 的基础用法,使用上一篇《 Redux 学习(一)》文章的知识点已经能够基本使用 redux 对项目进行状态管理了,现在来学一下 react-redux,同样,参考了尚硅谷在b站的学习视频

原理

需要按照如下模型图对项目进行修改,UI 组件只管显示,容器组件才是真正与 Redux 打交道的组件。 在这里插入图片描述

实现

connect()() 函数

容器组件主要就是靠 connect()() 函数,第一个括号里接受两个参数,一个参数是 redux 里面的状态 state,另一个是操作状态的方法,第二个括号接受 UI 组件(不用“<>”符号) 注意:使用 connect 函数之后就不用再向上一篇代码一样要监听 redux 里面的状态了。因为使用了 react-redux 的缘故。

显示容器组件

只要在本来要显示之前所谓的“UI”组件的地方引入并显示容器组件就行了。 但注意要在那里引入 store (也就是 redux 里面的 store) 作为 props 参数传给容器组件

{/* 给容器组件传递store */}
<CountContainer store={store} />

容器组件向UI组件传递方法与状态

见代码(来自尚硅谷)

//引入Count的UI组件
import CountUI from '../../components/Count'
//引入action
import {
	createIncrementAction,
	createDecrementAction,
	createIncrementAsyncAction
} from '../../redux/count_action'

//引入connect用于连接UI组件与redux
import {connect} from 'react-redux'

/* 
	1.mapStateToProps函数返回的是一个对象;
	2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
	3.mapStateToProps用于传递状态
*/
function mapStateToProps(state){
	return {count:state}
}

/* 
	1.mapDispatchToProps函数返回的是一个对象;
	2.返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value
	3.mapDispatchToProps用于传递操作状态的方法
*/
function mapDispatchToProps(dispatch){
	return {
		jia:number => dispatch(createIncrementAction(number)),
		jian:number => dispatch(createDecrementAction(number)),
		jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),
	}
}

//使用connect()()创建并暴露一个Count的容器组件
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)


UI 组件如何接受store

import React, { Component } from 'react'

export default class Count extends Component {

	state = {carName:'奔驰c63'}

	//加法
	increment = ()=>{
		const {value} = this.selectNumber
		this.props.jia(value*1)
	}
	//减法
	decrement = ()=>{
		const {value} = this.selectNumber
		this.props.jian(value*1)
	}
	//奇数再加
	incrementIfOdd = ()=>{
		const {value} = this.selectNumber
		if(this.props.count % 2 !== 0){
			this.props.jia(value*1)
		}
	}
	//异步加
	incrementAsync = ()=>{
		const {value} = this.selectNumber
		this.props.jiaAsync(value*1,500)
	}

	render() {
		//console.log('UI组件接收到的props是',this.props);
		return (
			<div>
				<h1>当前求和为:{this.props.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>
		)
	}
}