首页 > 其他分享 >第六章、react高级

第六章、react高级

时间:2023-01-05 23:12:13浏览次数:36  
标签:const counter 高级 dispatch react state 第六章 redux store

目录

十四、Redux的使用一

1、javascript纯函数
* javascript纯函数简单总结
    - 确定的输入,一定会产生确定的输出
    - 函数在执行过程中,不能产生副作用
* React中要求我们无论是函数还是class声明一个组件,这个组件都必须像纯函数一样,保护它们的props不被修改
* 在redux中,reducer也被要求是一个纯函数
2、为什么需要redux
* react是在视图层帮助我们解决了dom的渲染过程,但是state依然是留给我们自己来管理
    - UI = render(state)
* redux就是一个帮助我们管理state的容器:redux是javascript的状态容器,提供了可预测的状态管理
3、redux的核心理念
* store
* action
    - 所有数据的变化,必须通过派发(dispatch)action来更新
    - action是一个普通的javascript对象,用来描述这次更新的type和content
* reducer
    - reducer是一个纯函数
    - reducer做的事情就是将传入的state和action结合起来生成一个新的state
4、redux的三大原则
* 单一数据源
* state是只读的
* 使用纯函数来执行修改
5、redux的基本使用
// 安装:npm i redux
const redux = require("redux")

const initialState = {
  counter: 0
}

// reducer
function reducer(state = initialState, action) {
  switch (action.type) {
    case "INCREMENT":
      return {...state, counter: state.counter + 1}
    case "DECREMENT":
      return {...state, counter: state.counter - 1}
    case "ADD_NUMBER":
      return {...state, counter: state.counter + action.num}
    case "SUB_NUMBER":
      return {...state, counter: state.counter - action.num}
    default:
      return state
  }
}

// store(创建的时候需要传入一个reducer)
const store = redux.createStore(reducer)

// 订阅store的修改
store.subscribe(() => {
  console.log("counter:", store.getState().counter)
})

// actions
const action1 = {type: "INCREMENT"}
const action2 = {type: "DECREMENT"}
const action3 = {type: "ADD_NUMBER", num: 5}
const action4 = {type: "SUB_NUMBER", num: 12}

// 派发action
store.dispatch(action1)
store.dispatch(action2)
store.dispatch(action2)
store.dispatch(action3)
store.dispatch(action4)
6、node中对ES6模块化的支持
* node v13.2.0之前,需要进行如下操作
    - 在package.json中添加属性:"type": "module"
    - 在执行命令中添加如下选项:node --experimental-modules src/index.js
* node v13.2.0之后,只需要进行如下操作
    - 在package.json中添加属性:"type": "module"
* 注意:导入文件时,需要跟上.js后缀名
7、redux的结构化分
  • index.js
import store from "./store/index.js"
import {addAction, subAction, incAction, decAction} from "./store/actionCreators.js"

store.subscribe(() => {
  console.log(store.getState())
})

store.dispatch(addAction(10))
store.dispatch(addAction(15))
store.dispatch(subAction(8))
store.dispatch(subAction(5))
store.dispatch(incAction())
store.dispatch(decAction())
  • store/index.js
import redux from "redux"
import reducer from "./reducer.js"

const store = redux.createStore(reducer)

export default store
  • store/actionCreators.js
import {INCREMENT, DECREMENT, ADD_NUMBER, SUB_NUMBER} from "./constants.js"

export const addAction = num => ({
  type: ADD_NUMBER,
  num
})

export const subAction = num => ({
  type: SUB_NUMBER,
  num
})

export const incAction = () => ({
  type: INCREMENT
})

export const decAction = () => ({
  type: DECREMENT
})
  • store/reducer.js
import {INCREMENT, DECREMENT, ADD_NUMBER, SUB_NUMBER} from "./constants.js"

const defaultState = {
  counter: 0
}

function reducer(state = defaultState, action) {
  switch (action.type) {
    case INCREMENT:
      return {...state, counter: state.counter + 1}
    case DECREMENT:
      return {...state, counter: state.counter - 1}
    case ADD_NUMBER:
      return {...state, counter: state.counter + action.num}
    case SUB_NUMBER:
      return {...state, counter: state.counter - action.num}
    default:
      return state
  }
}

export default reducer
  • store/constants.js
export const INCREMENT = "INCREMENT"
export const DECREMENT = "DECREMENT"
export const ADD_NUMBER = "ADD_NUMBER"
export const SUB_NUMBER = "SUB_NUMBER"
8、react和redux结合
import React, {PureComponent} from "react";
/**
 * 1、react中使用和node中使用的唯一区别:redux引入方式不一样
 *     - node:import redux from "redux"
 *     - react:import * as redux from "redux"
 */
import store from "@/store";
import {addAction, subAction} from "@/store/actionCreators";

class Home extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      counter: store.getState().counter
    }
  }

  componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
      this.setState({
        counter: store.getState().counter
      })
    })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    return (<div>
      <h1>Home</h1>
      <h2>当前计数:{this.state.counter}</h2>
      <button onClick={e => this.increment()}>+1</button>
      <button onClick={e => this.addNumber(5)}>+5</button>
    </div>)
  }

  increment() {
    store.dispatch(addAction(1))
  }

  addNumber() {
    store.dispatch(addAction(5))
  }
}

class About extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      counter: store.getState().counter
    }
  }

  componentDidMount() {
    this.unsubscribe = store.subscribe(() => {
      this.setState({
        counter: store.getState().counter
      })
    })
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  render() {
    return (<div>
      <h1>About</h1>
      <h2>当前计数:{this.state.counter}</h2>
      <button onClick={e => this.decrement()}>-1</button>
      <button onClick={e => this.subNumber(5)}>-5</button>
    </div>)
  }

  decrement() {
    store.dispatch(subAction(1))
  }

  subNumber() {
    store.dispatch(subAction(5))
  }
}

export default class App extends PureComponent {
  render() {
    return (<>
      <Home/>
      <hr/>
      <About/>
    </>)
  }
}

十五、Redux的使用二

1、

标签:const,counter,高级,dispatch,react,state,第六章,redux,store
From: https://www.cnblogs.com/linding/p/17029086.html

相关文章

  • jQuery Mobile 高级设计模板
    来自:​​http://www.adobe.com/cn/devnet/dreamweaver/articles/dw-template-jquery-mobile.html​​下载:​​template_14-jquery-mobile-app.zip​​jQueryMobile是一款......
  • 前端react项目打包过程记录
    前端react项目打包过程记录1.打包命令npmrunbuild得到打包后的build文件夹,压缩build文件2.使用serve来运行发布版本该步骤可忽略npminstll-gserveserve-sbui......
  • Unity URP Shader之高级光照技术之SH
    首先声明以下素材和shader代码都来自Kerry佬,我只做整理和学习之用,写此随笔是为了做个笔记方便以后查阅。 SH,英文全称SphericalHarmonicsLighting,即球谐光照,主要用来模......
  • Unity URP Shader之高级光照技术之IBL
    首先声明以下素材和shader代码都来自Kerry佬,我只做整理和学习之用,写此随笔是为了做个笔记方便以后查阅。 IBL,英文全称ImageBasedLighting,即基于图像的照明,是一种通过......
  • react 收集表单数据 react-hook-form
    importReactfrom'react'importReactDOMfrom'react-dom'import{useForm}from'react-hook-form'functionApp(){const{register,handleSubmit,error......
  • React的useLayoutEffect和useEffect执行时机有什么不同
    我们先看下React官方文档对这两个hook的介绍,建立个整体认识useEffect(create,deps):该Hook接收一个包含命令式、且可能有副作用代码的函数。在函数组件主体内(这......
  • React循环DOM时为什么需要添加key
    一、React渲染流程和更新流程react渲染流程:jsx->虚拟dom->真实domreact更新流程:props/state改变->render函数重新执行->生成新的虚拟dom树->新旧虚拟dom树进......
  • 校招前端二面常考react面试题(边面边更)
    高阶组件高阶函数:如果一个函数接受一个或多个函数作为参数或者返回一个函数就可称之为高阶函数。高阶组件:如果一个函数接受一个或多个组件作为参数并且返回一个组件就......
  • 前端一面常考react面试题
    类组件(Classcomponent)和函数式组件(Functionalcomponent)之间有何不同类组件不仅允许你使用更多额外的功能,如组件自身的状态和生命周期钩子,也能使组件直接访问store......
  • 技术起底 | 高级驾驶辅助系统(ADAS)
    一)什么是ADASADAS(AdvancedDrivingAssistanceSystem,高级驾驶辅助系统),是利用安装在车上的各式各样的传感器(毫米波雷达、激光雷达、单\双目摄像头以及卫星导航),在汽车行驶......