持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第5天,点击查看活动详情
写在前面
在最近看了React之后,一直觉得学的懵懵然,虽然很多大佬的手写笔记,写的都很不错,但是我一直没有我想要的那种细无巨细,比如类式组件this指向问题的追根溯源,又比如三大实例属性简写的由来,总之我还是决定做一份事无巨细的笔记。
那就让我们开始吧!
求和案例_纯react版
实现效果
书写index入口文件、App组件
- index入口文件
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(<App/>,document.getElementById('root'))
- App组件
注意:记得引入子组件Count
import React, { Component } from 'react'
import Count from './components/Count'
export default class App extends Component {
render() {
return (
<div>
<Count/>
</div>
)
}
}
书写Count组件
- 书写基本结构、初始化状态
state = {count:0}
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>
<button >+</button>
<button >-</button>
<button }>当前求和为奇数再加</button>
<button }>异步加</button>
</div>
)
- 给button绑定点击事件
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
<button onClick={this.incrementAsync}>异步加</button>
- 书写事件方法
//加法
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)
}
求和案例_redux精简版
创建redux中最为核心的store对象
-
创建redux文件夹、创建一个store.js文件
-
引入createStore方法
//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore} from 'redux'
- 引入为Count组件服务的reducer
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
- 暴露store
//暴露store
export default createStore(countReducer)
创建reducer
1.该文件是用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数
2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
const initState = 0 //初始化状态 定义在函数外面更加清晰初始状态
export default function countReducer(preState=initState,action){ // 形参默认值
// console.log(preState);
//从action对象中获取:type、data
const {type,data} = action
//根据type决定如何加工数据
switch (type) {
case 'increment': //如果是加
return preState + data
case 'decrement': //若果是减
return preState - data
default:
return preState // 不加不减
}
}
整改Count组件
修改组件状态
- 将只有Count组件使用的属性可以保存在state属性中,共享的属性就交给reducer
引入store
import store from '../../redux/store'
- 获取初始值
注意:不能直接使用store(对象不能作为React节点)
- 获得状态
注意:store对象会调用reducer函数获得初始值。
<h1>当前求和为:{store.getState()}</h1>
- 使用store对象调用dispatch进而触发redux修改状态
store.dispatch({type:'increment',data:value*1})
- redux只负责修改状态,不会触发render方法更新页面
①在特定组件检测redux是否修改了状态,要是修改了就调用该组件的render
componentDidMount(){
//检测redux中状态的变化,只要变化,就调用render
store.subscribe(()=>{
this.setState({}) // 调用但是不更新状态
})
}
②在index.js入口文件中使用store.subscribe()检测整个App组件
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
ReactDOM.render(<App/>,document.getElementById('root'))
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
总结
(1).去除Count组件自身的状态
(2).src下建立:
-redux
-store.js
-count_reducer.js
(3).store.js:
1).引入redux中的createStore函数,创建一个store
2).createStore调用时要传入一个为其服务的reducer
3).记得暴露store对象
(4).count_reducer.js:
1).reducer的本质是一个函数,接收:preState,action,返回加工后的状态
2).reducer有两个作用:初始化状态,加工状态
3).reducer被第一次调用时,是store自动触发的,
传递的preState是undefined,
传递的action是:{type:'@@REDUX/INIT_a.2.b.4}
(5).在index.js中监测store中状态的改变,一旦发生改变重新渲染<App/>备注:redux只负责管理状态,至于状态的改变驱动着页面的展示,要靠我们自己写。
求和案例_redux完整版
action对象(将要修改状态的方法封装在内)
-
在redux文件夹下创建count_action.js文件
-
简写箭头函数的时候,返回的是一个对象那么需要在对象外面添加一个()。
/*
该文件专门为Count组件生成action对象
*/
import {INCREMENT,DECREMENT} from './constant'
export const createIncrementAction = data => ({type:INCREMENT,data})
export const createDecrementAction = data => ({type:DECREMENT,data})
在Count组件中添加action对象暴露的方法
//引入actionCreator,专门用于创建action对象
import {createIncrementAction,createDecrementAction} from '../../redux/count_action'
constant模块
-
该模块是用于定义action对象中type类型的常量值,目的只有一个:便于管理的同时防止程序员单词写错
-
这里constant.js 放置容易写错的type值
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
在count_action、count_reducer内部引入constant模块
import {INCREMENT,DECREMENT} from './constant'
求和案例_异步action版
-
不在Count组件内部书写异步函数
-
在action-create中书写异步action
为什么异步action的值是一个函数:因为只有函数可以开启一个异步任务
- 不用在action文件内引入store对象(异步action本身就是store对象调用)
//异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的。
export const createIncrementAsyncAction = (data,time) => {
return (dispatch)=>{ // 记住传入dispatch参数
setTimeout(()=>{
dispatch(createIncrementAction(data))
},time)
}
}
store对象调用异步action(添加中间件)
添加中间件
yarn add redux-thunk
- store对象引入执行中间件
在store.js文件内部
//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware} from 'redux'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//暴露store
export default createStore(countReducer,applyMiddleware(thunk))
总结
(1).明确:延迟的动作不想交给组件自身,想交给action
(2).何时需要异步action:想要对状态进行操作,但是具体的数据靠异步任务返回。
(3).具体编码:
1).yarn add redux-thunk,并配置在store中
2).创建action的函数不再返回一般对象,而是一个函数,该函数中写异步任务。
3).异步任务有结果后,分发一个同步的action去真正操作数据。
(4).备注:异步action不是必须要写的,完全可以自己等待异步任务的结果了再去分发同步action。
对react-redux的理解
Facebook 出的 react-redux插件库
理解
1. 一个react插件库
2. 专门用来简化react应用中使用redux
react-redux模型图
连接容器组件与UI组件
UI组件
1) 只负责 UI 的呈现,不带有任何业务逻辑
2) 通过props接收数据(一般数据和函数)
3) 不使用任何 Redux 的 API
4) 一般保存在components文件夹下
容器组件
1) 负责管理数据和业务逻辑,不负责UI的呈现
2) 使用 Redux 的 API
3) 一般保存在containers文件夹下,对应什么UI组件就创建一个对应名字的文件夹(这里在containers文件夹下创建一个count文件夹在创建容器组件)
创建容器组件
- 安装react-redux
yarn add react-redux
- App组件里面引入的是容器组件,UI组件里面不可以引入store相关的东西
容器组件正确引入store对象
- 在容器组件内部删除store
- 在App组件引入store、再传递给容器组件
import React, { Component } from 'react'
import Count from './containers/Count'
import store from './redux/store'
export default class App extends Component {
render() {
return (
<div>
{/* 给容器组件传递store */}
<Count store={store} />
</div>
)
}
}
react-redux基本使用
父子关系查看
给UI组件传递属性
- 书写一个函数,函数的返回值是一个对象。
返回的对象中的key就作为传递给UI组件props的key,value就作为传递给UI组件props的value(value可以是一个状态值,也可以是一个状态方法)
- 将函数作为一个参数传递给connect函数
//使用connect()()创建并暴露一个Count的容器组件
export default connect(mapStateToProps,mapDispatchToProps)(CountUI)
- 实现效果图
容器组件获取状态
-
不需要引入store对象,使用store.getstate()
-
react-redux 在调用函数的时候就直接将状态已经传递给函数了。
function a (state) {
return {count:state}
}
容器组件获取状态方法
-
不需要引入store对象
-
react-redux 在调用函数的时候就直接将dispatch已经传递给函数了。
function b(dispatch) {
return jia:number => dispatch(createIncrementAction(number))
}
如果函数返回的不是一个对象
1.返回状态的函数
2.返回操作状态函数的函数
对2个函数的总结
/*
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)),
}
}
优化1_简写mapDispatch
编码角度的简写
- 箭头函数
mapDispatchToProps = state => ({count:state})
mapDispatchToProps = dispatch =>
(
{
jia:number => dispatch(createIncrementAction(number)),
jian:number => dispatch(createDecrementAction(number)),
jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),
}
)
- 直接将函数书写到connect函数内
export default connect(
state => ({count:state}),
dispatch =>
(
{
jia:number => dispatch(createIncrementAction(number)),
jian:number => dispatch(createDecrementAction(number)),
jiaAsync:(number,time) => dispatch(createIncrementAsyncAction(number,time)),
}
)
)(CountUI)
- mapDispatchToProps的简写(对象形式)
react-redux 如自动分发action对象,所以只需要将action对象传递给UI组件即可
//mapDispatchToProps的简写
{
jia:createIncrementAction,
jian:createDecrementAction,
jiaAsync:createIncrementAsyncAction,
}
总结
(1).明确两个概念:
1).UI组件:不能使用任何redux的api,只负责页面的呈现、交互等。
2).容器组件:负责和redux通信,将结果交给UI组件。
(2).如何创建一个容器组件————靠react-redux 的 connect函数
connect(mapStateToProps,mapDispatchToProps)(UI组件)
-mapStateToProps:映射状态,返回值是一个对象
-mapDispatchToProps:映射操作状态的方法,返回值是一个对象
(3).备注1:容器组件中的store是靠props传进去的,而不是在容器组件中直接引入
(4).备注2:mapDispatchToProps,也可以是一个对象
Provider组件的使用
容器组件自带检测能力
- 不用在使用一个store.subscribe()
//不用使用
store.subscribe(()=>{
ReactDOM.render(<App/>,document.getElementById('root'))
})
改变传递store对象给容器组件的方式
无需自己给容器组件传递store,给<App/>包裹一个<Provider store={store}>即可。
import store from './redux/store'
import {Provider} from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root')
)
整合文件容器组件和UI组件
容器组件和UI组件整合一个文件
- 合并之后所属文件夹
- 将UI组件的代码复制到容器组件
- 将UI组件默认暴露删除
优化总结
(1).容器组件和UI组件整合一个文件
(2).无需自己给容器组件传递store,给<App/>包裹一个<Provider store={store}>即可。
(3).使用了react-redux后也不用再自己检测redux中状态的改变了,容器组件可以自动完成这个工作。
(4).mapDispatchToProps也可以简单的写成一个对象
(5).一个组件要和redux“打交道”要经过哪几步?
(1).定义好UI组件---不暴露
(2).引入connect生成一个容器组件,并暴露,写法如下:
connect(
state => ({key:value}), //映射状态
{key:xxxxxAction} //映射操作状态的方法
)(UI组件)
(4).在UI组件中通过this.props.xxxxxxx读取和操作状态
数据共享_编写Person组件
将action、reducer文件集中式管理
注意:记得修改对应的引入文件的路径
创建Person组件
- 创建Person.js文件
2.在App组件里面引入Person组件
import React, { Component } from 'react'
import Count from './containers/Count'
import Person from './containers/Person'
export default class App extends Component {
render() {
return (
<div>
<Count/>
<hr/>
<Person/>
</div>
)
}
}
3.书写Person组件
import React, { Component } from 'react'
import {createAddPersonAction} from '../../redux/actions/person'
export default class Person extends Component {
addPerson = ()=>{
const name = this.nameNode.value
const age = this.ageNode.value
console.log(name,age)
}
render() {
return (
<div>
<h2>我是Person组件</h2>
<input ref={c=>this.nameNode = c} type="text" placeholder="输入名字"/>
<input ref={c=>this.ageNode = c} type="text" placeholder="输入年龄"/>
<button onClick={this.addPerson}>添加</button>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
)
}
}
编写Person组件的reducer
书写常量
- constant.js文件
export const ADD_PERSON = 'add_person'
书写Perosn组件对应的action
import {ADD_PERSON} from '../constant'
//创建增加一个人的action动作对象
export const createAddPersonAction = personObj => ({type:ADD_PERSON,data:personObj})
书写Perosn组件对应的reducers
import {ADD_PERSON} from '../constant'
//初始化人的列表
const initState = [{id:'001',name:'tom',age:18}]
export default function personReducer(preState=initState,action){
// console.log('personReducer@#@#@#');
const {type,data} = action
switch (type) {
case ADD_PERSON: //若是添加一个人
return [data,...preState]
default:
return preState
}
}
使用nanoid书写对象的id值
yarn add nanoid
- 引入和使用nanoid
import {nanoid} from 'nanoid'
const personObj = {id:nanoid(),name,age}
数据共享_完成数据共享
在store中引入多个组件的redux
//引入为Count组件服务的reducer
import countReducer from './reducers/count'
//引入为Count组件服务的reducer
import personReducer from './reducers/person'
将多个组件的reducer合并
- 使用redux封装的combinReducers
- 引入createStore
//引入createStore,专门用于创建redux中最为核心的store对象
import {createStore,applyMiddleware,combineReducers} from 'redux'
- 汇总所有的reducer
//汇总所有的reducer变为一个总的reducer
const allReducer = combineReducers({
he:countReducer,
rens:personReducer
})
- 暴露store
//暴露store
export default createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))
注意: combinReducers传入的对象就是redux保存的“总”状态对象。
- 修改取状态代码
- redux现在存储的是一个对象使用,现在是要取状态中的属性值
// 之前state是一个值
state => ({
count:state
})
// 现在state是一个对象
state => ({
count:state.he,
renshu:state.rens.length
})
总结 求和案例_react-redux数据共享版
(1).定义一个Pserson组件,和Count组件通过redux共享数据。 (2).为Person组件编写:reducer、action,配置constant常量。 (3).重点:Person的reducer和Count的Reducer要使用combineReducers进行合并,合并后的总状态是一个对象!!! (4).交给store的是总reducer,最后注意在组件中取出状态的时候,记得“取到位”。
纯函数
纯函数
1. 一类特别的函数: 只要是同样的输入(实参),必定得到同样的输出(返回)
2. 必须遵守以下一些约束
1) 不得改写参数数据
2) 不会产生任何副作用,例如网络请求,输入和输出设备
3) 不能调用Date.now()或者Math.random()等不纯的方法
3. redux的reducer函数必须是一个纯函数
redux开发者工具
使用上redux调试工具
安装chrome浏览器插件
下载工具依赖包
npm install --save-dev redux-devtools-extension
store中进行配置
//引入redux-devtools-extension
import {composeWithDevTools} from 'redux-devtools-extension'
//暴露store
export default createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))
浏览器使用插件
redux 求和案例_最终版
总结
(1).所有变量名字要规范,尽量触发对象的简写形式。
(2).reducers文件夹中,编写index.js专门用于汇总并暴露所有的reducer
/*
该文件用于汇总所有的reducer为一个总的reducer(之前这些代码是写在store.js内部的)
*/
//引入combineReducers,用于汇总多个reducer
import {combineReducers} from 'redux'
//引入为Count组件服务的reducer
import count from './count'
//引入为Person组件服务的reducer
import persons from './person'
//汇总所有的reducer变为一个总的reducer
export default combineReducers({
count,
persons
})
项目打包
终端命令
npm run build
serve -s build