• react hooks方法获取不到最新的state解决方法


    问题
    在setState方法执行之后,再执行自定义的方法,这个自定义方法里面获取不到最新的state状态

    import React, {useState} from "react";
    import { Button } from "antd"

    const Demo = () => {
    const [num, changeNum] = useState(1)
    const [str, changeStr] = useState("现在数字是1")

    const getNum = () => {
    const newStr = "现在数字是" + num
    console.log(newStr)
    changeStr(newStr)
    }

    const setNum = () => {
    // 使用 async await 自执行函数 setTimeout 都没用
    changeNum(num + 1)
    // 执行之后 getNum里拿不到最新的state
    getNum()
    }

    return (
    <div>
    <Button onClick={setNum}>点我+1</Button>
    <div>{num}</div>
    <div>{str}</div>
    </div>
    )
    }

    export default Demo

    解决方法
    第一种

    通过useEffect方法监听num 再去触发getNum函数

    useEffect(() => {
    getNum()
    }, [num])

    const getNum = () => {
    const newStr = "现在数字是" + num
    changeStr(newStr)
    }

    const setNum = () => {
    changeNum(num + 1)
    }

    第二种

    const numRef = useRef(1)
    const [num, changeNum] = useState(numRef.current)
    const [str, changeStr] = useState("现在数字是1")

    const getNum = () => {
    const newStr = "现在数字是" + numRef.current
    changeStr(newStr)
    }

    const setNum = () => {
    numRef.current = num + 1
    changeNum(numRef.current)
    getNum()
    }

    完整第一种代码

    import React, {useState, useEffect} from "react";
    import { Button } from "antd"

    const Demo = () => {
    const [num, changeNum] = useState(1)
    const [str, changeStr] = useState("现在数字是1")

    useEffect(() => {
    getNum()
    }, [num])

    const getNum = () => {
    const newStr = "现在数字是" + num
    changeStr(newStr)
    }

    const setNum = () => {
    changeNum(num + 1)
    }

    return (
    <div>
    <Button onClick={setNum}>点我+1</Button>
    <div>{num}</div>
    <div>{str}</div>
    </div>
    )
    }

    export default Demo

    完整第二种代码

    import React, {useState, useEffect, useRef} from "react";
    import { Button } from "antd"

    const Demo = () => {
    const numRef = useRef(1)
    const [num, changeNum] = useState(numRef.current)
    const [str, changeStr] = useState("现在数字是1")

    const getNum = () => {
    const newStr = "现在数字是" + numRef.current
    changeStr(newStr)
    }

    const setNum = () => {
    numRef.current = num + 1
    changeNum(numRef.current)
    getNum()
    }

    return (
    <div>
    <Button onClick={setNum}>点我+1</Button>
    <div>{num}</div>
    <div>{str}</div>
    </div>
    )
    }

    export default Demo

  • 相关阅读:
    一、初识数据库
    面向对象—基础、名称空间、三大特性
    六、内置函数
    五、迭代器、生成器、装饰器
    四、global和nonlocal、函数名应用、格式化输出
    三、名称空间
    二、函数的参数
    shell脚本
    线性代数
    [模块] python调用java代码-jpype
  • 原文地址:https://www.cnblogs.com/ranyonsue/p/14986938.html
Copyright © 2020-2023  润新知