如果我右擊紅色的 DivElement,我想改變我的狀態
由于狀態已經改變,所以我想我可以看到console.log
但它不起作用
這是我的代碼
import { useState, useRef, useEffect } from "react";
function Main() {
const [testState, setTestState] = useState(0);
const testRef = useRef(null);
function clickHandler(event) {
setTestState(testState 1);
}
useEffect(() => {
if (!testRef) return;
testRef.current.addEventListener('contextmenu', (event) => { clickHandler(event) });
}, [testRef]);
useEffect(() => {
console.log('testState: ', testState);
}, [testState]);
return (
<div
ref={testRef}
style={{width: '100%', display: 'block', height: '32px', backgroundColor: 'red'}}
/>
);
}
export default Main;
uj5u.com熱心網友回復:
當您參考您的狀態時,問題就出現了,請記住 setState 是異步執行的(將 setState 視為重新渲染組件的請求)。
通過更改您setTestState(testState 1); setTestState((oldVal) => oldVal 1);的示例將起作用。看看這個 stackblitz例子
問候,
uj5u.com熱心網友回復:
您應該在 clickHandler 上使用cleanup functionand preventDefault。
import { useState, useRef, useEffect, useCallback } from "react";
function Main() {
const [testState, setTestState] = useState(0);
const testRef = useRef(null);
const clickHandler = useCallback((event) => {
event.preventDefault();
setTestState((test) => test 1);
}, []);
useEffect(() => {
const refElement = testRef.current;
refElement.addEventListener("contextmenu", clickHandler);
return () => refElement.removeEventListener("contextmenu", clickHandler); //cleanup function
}, [clickHandler]);
useEffect(() => {
console.log("testState: ", testState);
}, [testState]);
return (
<div
ref={testRef}
style={{
width: "100%",
display: "block",
height: "32px",
backgroundColor: "red"
}}
/>
);
}
export default Main;
作業代碼沙盒
uj5u.com熱心網友回復:
這是一個作業代碼片段:
function Main() {
const [testState, setTestState] = useState(0);
const testRef = useRef(null);
useEffect(() => {
function clickHandler(event) {
setTestState((old) => old 1);
}
if (!testRef) return;
const ref = testRef.current;
ref.addEventListener("contextmenu", clickHandler);
return () => ref.removeEventListener("contextmenu", clickHandler);
}, [testRef, testState]);
useEffect(() => {
console.log("testState: ", testState);
}, [testState]);
return (
<div
ref={testRef}
style={{
width: "100%",
display: "block",
height: "32px",
backgroundColor: "red",
}}
/>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322055.html
標籤:javascript 反应
