【问题标题】:how can i get useState value inside useCallback (react hook)我如何在 useCallback 中获取 useState 值(反应钩子)
【发布时间】:2021-08-05 07:41:22
【问题描述】:

我无法获得 useCallback 内部的 useState 值。当我运行下面的代码时,

import React, { useCallback, useEffect, useRef, useState } from 'react';

const DBLab = () => {
    const [hashHistory, setHashHistory] = useState("initial_value");
    const [inputValue, setInputValue] = useState("");
    const didAuthMountRef = useRef(false);

    const set = useCallback(() => {
        const decodeHash = decodeURI(window.location.hash);
        console.log();
        console.log("decodeHash: " + decodeHash);
        console.log("hashHistory: "+ hashHistory);
        setHashHistory(decodeHash);
    },[hashHistory]);

    useEffect(() => {
        const startFunc = async() => {
            set();
            window.addEventListener('hashchange', set);
            didAuthMountRef.current = true;
        }
        if(!didAuthMountRef.current) {
            startFunc();
        }
    }, [set]);
    return (
        <div>
            <h1>dblab</h1>
            <h1>{hashHistory}</h1>
            <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)}/>
        </div>
    )
}

export default DBLab;

在网络控制台中,我得到了

decodeHash: #/dblab#first

hashHistory: initial_value

这是对的。但是当我将 url 更改为 http://localhost:3000/#/dblab#next 时,我得到了


decodeHash: #/dblab#next

hashHistory: initial_value

这是错误的。因为 hashHistory 没有改变。但这不是 useState 问题。因为我在屏幕上用&lt;h1&gt;{hashHistory}&lt;/h1&gt; 看到的hashHistory 是#/dblab#next,这是正确的哈希。

如何在 useCallback 中获取正确的 hashHistory?

ps。我必须使用useCallback

【问题讨论】:

标签: reactjs react-hooks use-state usecallback


【解决方案1】:
useEffect(() => {
    const startFunc = () => {
        if(!didAuthMountRef.current) {
            set();
            didAuthMountRef.current = true;
        }
        window.addEventListener('hashchange', set);
    }
    startFunc();
    return ()=> {
        window.removeEventListener('hashchange', set);
    }
}, [set]);

逻辑问题

【讨论】:

  • 太聪明了!但是你知道为什么useEffect 添加evnetListener 一次吗?不是每次执行'set'函数都会执行'useEffect'吗?
  • @importJWE 不,每次set 函数的身份发生变化时都会执行。
  • @importJWE set(exec)=>hasHistory(change)=>set(change)=>useEffect(release)=>useEffect(exec)
  • @AKX 身份更改?
  • @importJWE 见reactjs.org/docs/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2020-08-03
  • 2020-11-30
  • 2021-04-10
相关资源
最近更新 更多