最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

react中(含hooks)同步獲取state值的方式

 更新時(shí)間:2022年08月08日 10:34:04   作者:daoke_li  
這篇文章主要介紹了react(含hooks)中同步獲取state值的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

react(含hooks)同步獲取state值

環(huán)境

"dependencies": {
? ? "babel-plugin-transform-decorators-legacy": "^1.3.5",
? ? "customize-cra": "^1.0.0",
? ? "rc-form": "^2.4.11",
? ? "react": "^17.0.1",
? ? "react-app-rewired": "^2.1.8",
? ? "react-dom": "^17.0.1",
? ? "react-router-dom": "^5.2.0",
? ? "react-scripts": "^4.0.1",
? ? "redux": "^4.0.5"
? },

代碼示例

hooks

import {useState} from "react";
export default function Pre04SetStateSync() {
? ? const [counter, setCounter] = useState(0)
? ? const add = () => {
? ? ? ? setCounter(counter + 1)
? ? ? ? console.log({counter})
? ? }
? ? return <>
? ? ? ? <h3>同步SetState</h3>
? ? ? ? <p>請(qǐng)觀察控制臺(tái)</p>
? ? ? ? <button onClick={add}>counter: {counter}</button>
? ? </>
}

class 

export default class Pre04SetStateSync extends React.Component{
? ? state = {
? ? ? ? counter:0
? ? }
? ? add = () => {
? ? ? ? this.setState({counter:this.state.counter + 1})
? ? ? ? console.log('~~this.state.counter',this.state.counter)
? ? }
? ? render() {
? ? ? ? return <>
? ? ? ? ? ? <h3>同步SetState</h3>
? ? ? ? ? ? <p>請(qǐng)觀察控制臺(tái)</p>
? ? ? ? ? ? <button onClick={this.add}>counter: {this.state.counter}</button>
? ? ? ? </>
? ? }
}

hooks結(jié)構(gòu)中的setCounter(xxx)相當(dāng)于class組件寫法中setState({counter: xxx})

可以對(duì)比控制臺(tái)看到,這樣直接setCounter(setState)后立即輸出的counter的是上一次的值,而按鈕上顯示正確,說(shuō)明本次更新是異步的(react這樣設(shè)計(jì)是為了批量更新而提高性能),打印時(shí)counter還沒來(lái)得及改變。如果需要set完后立即取到counter的最新值,可以按如下方法實(shí)現(xiàn)同步的效果。

異步寫成同步的方法

1. 寫在setTimeout中

注意,只適用于class組件

add = () => {
? ? setTimeout(()=>{
? ? ? ? this.setState({counter:this.state.counter + 1})
? ? ? ? console.log('~~this.state.counter',this.state.counter)
? ? },0)
}

2. 合成事件使用原生事件替代

注意,只適用于class組件

// 原生事件
export default class Pre04SetStateSync extends React.Component {
? ? state = {
? ? ? ? counter: 0
? ? }
? ? componentDidMount() {
? ? ? ? document.querySelector('#btn').addEventListener('click', this.add)
? ? }
? ? add = () => {
? ? ? ? this.setState({counter: this.state.counter + 1})
? ? ? ? console.log('~~this.state.counter', this.state.counter)
? ? }
? ? render() {
? ? ? ? return <>
? ? ? ? ? ? <h3>同步SetState</h3>
? ? ? ? ? ? <p>請(qǐng)觀察控制臺(tái)</p>
? ? ? ? ? ? <button id='btn'>counter: {this.state.counter}</button>
? ? ? ? </>
? ? }
}

3. 寫入setState的回調(diào)函數(shù)中

注意,只適用于class組件

export default class Pre04SetStateSync extends React.Component {
? ? state = {
? ? ? ? counter: 0
? ? }
? ? add = () => {
? ? ? ? this.setState({counter: this.state.counter + 1}, ()=>{
? ? ? ? ? ? console.log('~~this.state.counter', this.state.counter)
? ? ? ? })
? ? }
? ? render() {
? ? ? ? return <>
? ? ? ? ? ? <h3>同步SetState</h3>
? ? ? ? ? ? <p>請(qǐng)觀察控制臺(tái)</p>
? ? ? ? ? ? <button onClick={this.add}>counter: {this.state.counter}</button>
? ? ? ? </>
? ? }
}

4. 連續(xù)setState的問題

注意,class組件和hooks都可以

如果將add改為先加1再加2,會(huì)發(fā)現(xiàn)代碼只執(zhí)行了最后一個(gè)加2,加1被忽略了,如:

const add = () => {
? ? setCounter(counter + 1)
? ? setCounter(counter + 2)
}

解決方法是將setState的參數(shù)寫成函數(shù)形式

const add = () => {
? ? setCounter(counter => counter + 1)
? ? setCounter(counter => counter + 2)
}

5. 使用副作用useEffect

注意,只適用于hooks

export default function Pre04SetStateSync() {
? ? const [counter, setCounter] = useState(0)
? ? const add = () => {
? ? ? ? setCounter(counter + 1)
? ? }
? ? useEffect(() => {
? ? ? ? console.log({counter})
? ? }, [counter])
? ??
? ? return <>
? ? ? ? <h3>同步SetState</h3>
? ? ? ? <p>請(qǐng)觀察控制臺(tái)</p>
? ? ? ? <button onClick={add}>counter: {counter}</button>
? ? </>
}

react hooks常用方法

1.useState

function Example01(){
? ? const [ count, setCount ] = useState(0) ?//聲明
? ? return(
? ? ? ? <div>
? ? ? ? ? ? <p>{count}</p> ?//讀取
? ? ? ? ? ? <button onClick={()=>setCount(count+1)}>計(jì)數(shù)</button> // 使用(修改)
? ? ? ? </div>
? ? )
}

2.useEffect

1.React首次渲染和之后的每次渲染都會(huì)調(diào)用一遍useEffect函數(shù),而之前我們要用兩個(gè)生命周期函數(shù)分別表示首次渲染(componentDidMonut)和更新導(dǎo)致的重新渲染(componentDidUpdate)

2.useEffect中定義的函數(shù)的執(zhí)行不會(huì)阻礙瀏覽器更新視圖,也就是說(shuō)這些函數(shù)時(shí)異步執(zhí)行的,而componentDidMonut和componentDidUpdate中的代碼都是同步執(zhí)行的。

注意:

如果useEffect后面沒有依賴:

這種時(shí)候每次每次頁(yè)面更新都會(huì)執(zhí)行

useEffect(()=>{
? ? console.log('執(zhí)行');
})

如果后面為空

頁(yè)面初始的時(shí)候執(zhí)行一次

useEffect(()=>{
? ? console.log('執(zhí)行');
},[])

如果后面有值且不為空

只有當(dāng)count改變時(shí)才會(huì)被觸發(fā)

useEffect(()=>{
? ? console.log('執(zhí)行');
},[count])

使用useEffect解綁,組件卸載的時(shí)候,比如需要清除計(jì)時(shí)器等:

但是當(dāng)傳空數(shù)組[]時(shí),就是當(dāng)組件將被銷毀時(shí)才進(jìn)行解綁,這也就實(shí)現(xiàn)了componentWillUnmount的生命周期函數(shù)。

function Index() {
? ? useEffect(()=>{
? ? ? ? console.log('useEffect=>Index')
? ? ? ? return ()=>{
? ? ? ? ? ? console.log('Index頁(yè)面離開')
? ? ? ? }
? ? },[])
? ? return <h2>測(cè)試解綁</h2>;
}

3.useContext上下文傳值

1.父組件:

const CountContext = createContext() ?//引入
function Example01(){
? ? const [ count, setCount ] = useState(0)
? ? return(
? ? ? ? <div>
? ? ? ? ? ? <p>{count}</p>
? ? ? ? ? ? <button onClick={()=>setCount(count+1)}>計(jì)數(shù)</button>
? ? ? ? ? ? <CountContext.Provider value={count}> ?//使用包裹子組件傳遞值
? ? ? ? ? ? ? ? <ChildContent/>
? ? ? ? ? ? </CountContext.Provider> ? ? ?
? ? ? ? </div>
? ? )
}

2.子組件:

function ChildContent(){
? ? ?const context = useContext(CountContext)?
? ? ?return(
? ? ? ? ?<p>{context}</p>
? ? ?)
}

4.useReducer

它也是React hooks提供的函數(shù),可以增強(qiáng)我們的Reducer,實(shí)現(xiàn)類似Redux的功能。

import React, { useReducer ?} from 'react'
function Example5(){
? ? const [ count, dispatch ] = useReducer((state,action)=>{ ?
? ? ? ? ? ? ? switch(action){ ? //通過(guò)判斷對(duì)應(yīng)的action,去執(zhí)行對(duì)應(yīng)的方法
? ? ? ? ? ? case 'add':
? ? ? ? ? ? ? ? return state+1
? ? ? ? ? ? case 'sub':
? ? ? ? ? ? ? ? return state-1
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? return state
? ? ? ? }
? ? },1)
? ? return(
? ? ? ? <div>
? ? ? ? ? ? <p>{count}</p>
? ? ? ? ? ? <button onClick={()=>dispatch('add')}>add</button> ?//通過(guò)dispatch,傳遞對(duì)應(yīng)的action,調(diào)用對(duì)應(yīng)的方法
? ? ? ? ? ? <button onClick={()=>dispatch('sub')}>sub</button>
? ? ? ? </div>
? ? )
}
export default Example5

5.useMemo

useMemo主要用來(lái)解決使用React hooks產(chǎn)生的無(wú)用渲染的性能問題。

只要使用useMemo,然后給她傳遞第二個(gè)參數(shù),參數(shù)匹配成功,才會(huì)執(zhí)行。

1.在父組件里面,傳遞對(duì)應(yīng)需要的參數(shù)

import React , {useState,useMemo} from 'react';
function Example7(){
? ? const [one , setOne] = useState('第一個(gè)的狀態(tài)')
? ? const [two , setTwo] = useState('志玲待客狀態(tài)')
? ? return (
? ? ? ? <>
? ? ? ? ? ? <button onClick={()=>{setOne(new Date().getTime())}}>第一個(gè)</button>
? ? ? ? ? ? <button onClick={()=>{setTwo(new Date().getTime())}}>第二個(gè)</button>
? ? ? ? ? ? <ChildComponent name={one}>{two}</ChildComponent>
? ? ? ? </>
? ? )
}

2.父組件調(diào)用子組件

function ChildComponent({name,children}){
? ? function changeXiaohong(name){
? ? ? ? return name
? ? }
?const actionXiaohong = useMemo(()=>changeXiaohong(name),[name])
? ? return (
? ? ? ? <>
? ? ? ? ? ? <div>{actionXiaohong}</div>
? ? ? ? ? ? <div>{children}</div>
? ? ? ? </>
? ? )
}

6.useRef

用useRef獲取React JSX中的DOM元素,獲取后你就可以控制DOM的任何東西了。但是一般不建議這樣來(lái)作,React界面的變化可以通過(guò)狀態(tài)來(lái)控制

import React, { useRef } from 'react'
function Example8(){
? ? const inputRef ?= useRef(null)
? ? const onButtonClick=()=>{
? ? ? ? inputRef.current.value='THIS IS INPUT'
? ? ? ? console.log(inputRef);
? ? }
? ? return(
? ? ? ? <div>
? ? ? ? ? ? <input type="text" ref={inputRef}/>
? ? ? ? ? ? <button onClick = {onButtonClick}>顯示</button>
? ? ? ? </div>
? ? )
}
export default Example8

保存普通變量

import React, { useRef,useState } from 'react'
function Example8(){
? ? const inputRef ?= useRef(null)
? ? const onButtonClick=()=>{
? ? ? ? inputRef.current.value='THIS IS INPUT'
? ? ? ? console.log(inputRef);
? ? }
? ? ?const [state, setstate] = useState('inputValue') ?//聲明一個(gè)變量
? ? return(
? ? ? ? <div>
? ? ? ? ? ? <input type="text" ref={inputRef}/>
? ? ? ? ? ? <button onClick = {onButtonClick}>顯示</button>
? ? ? ? ? ? <input value={state} type="text" onChange={(e)=>setstate(e.target.value)}/> ?//綁定對(duì)應(yīng)的值以及綁定onChange事件
? ? ? ? </div>
? ? )
}
export default Example8

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • React-Native 橋接iOS原生開發(fā)詳解

    React-Native 橋接iOS原生開發(fā)詳解

    本篇文章主要介紹了React-Native 橋接iOS原生開發(fā)詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-01-01
  • hooks寫React組件的5個(gè)注意細(xì)節(jié)詳解

    hooks寫React組件的5個(gè)注意細(xì)節(jié)詳解

    這篇文章主要為大家介紹了hooks寫React組件的5個(gè)需要注意的細(xì)節(jié)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-03-03
  • React 原理詳解

    React 原理詳解

    這篇文章主要介紹了深入理解react的原理,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2021-10-10
  • React中井字棋游戲的實(shí)現(xiàn)示例

    React中井字棋游戲的實(shí)現(xiàn)示例

    本文主要介紹了React中井字棋游戲的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-08-08
  • create-react-app全家桶router?mobx全局安裝配置

    create-react-app全家桶router?mobx全局安裝配置

    這篇文章主要為大家介紹了create-react-app全家桶router?mobx全局安裝配置,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • react中使用heatmap.js實(shí)現(xiàn)熱力圖的繪制

    react中使用heatmap.js實(shí)現(xiàn)熱力圖的繪制

    heatmap.js?是一個(gè)用于生成熱力圖的?JavaScript?庫(kù),React?是一個(gè)流行的?JavaScript?庫(kù),用于構(gòu)建用戶界面,本小編給大家介紹了在React?應(yīng)用程序中使用heatmap.js實(shí)現(xiàn)熱力圖的繪制的示例,文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12
  • 一文教會(huì)你用redux實(shí)現(xiàn)computed計(jì)算屬性

    一文教會(huì)你用redux實(shí)現(xiàn)computed計(jì)算屬性

    在computed中,可以定義一些屬性,即計(jì)算屬性,下面這篇文章主要給大家介紹了關(guān)于如何利用redux實(shí)現(xiàn)computed計(jì)算屬性的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-05-05
  • React中Provider組件詳解(使用場(chǎng)景)

    React中Provider組件詳解(使用場(chǎng)景)

    這篇文章主要介紹了React中Provider組件使用場(chǎng)景,使用Provider可以解決數(shù)據(jù)層層傳遞和每個(gè)組件都要傳props的問題,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2024-02-02
  • React手寫簽名組件react-signature實(shí)現(xiàn)簽字demo

    React手寫簽名組件react-signature實(shí)現(xiàn)簽字demo

    這篇文章主要為大家介紹了React手寫簽名組件react-signature實(shí)現(xiàn)簽字demo,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • react build 后打包發(fā)布總結(jié)

    react build 后打包發(fā)布總結(jié)

    這篇文章主要介紹了react build 后打包發(fā)布總結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-08-08

最新評(píng)論

涪陵区| 元谋县| 军事| 逊克县| 三穗县| 崇文区| 靖宇县| 肃北| 青岛市| 集安市| 四子王旗| 新余市| 平泉县| 临高县| 盈江县| 焦作市| 涟水县| 沙田区| 前郭尔| 蒙自县| 长兴县| 丁青县| 浑源县| 和平县| 平度市| 来宾市| 朝阳市| 昭苏县| 南靖县| 南溪县| 定日县| 津南区| 桦甸市| 通州市| 孟津县| 鲁山县| 三亚市| 桐柏县| 沂南县| 拉萨市| 内乡县|