React 函数式组件获取不到变量值?
import React, { useEffect, useState } from 'react';
const Test = () => {
let test = null;
useEffect(() => {
test = 123;
}, [])
const testClick = () => {
console.log(test) // undefined
}
return(<button onClick={testClick}>点击</button>)
}
请问大佬们这是为啥?我难以理解...页面加载完毕的时候赋值给test,按理说test已经有值了,为啥打印不出来呢?
回复
1个回答

test
2024-07-16
因为你的test
变量定义在组件内部, 在每一次Test组件渲染时,test
变量都会被重新赋值成null
而useEffect却不会在执行 所以是null 建议是使用useRef
e.g.
import React, { useEffect, useState } from 'react';
const Test = () => {
const test = useRef(null);
useEffect(() => {
test.current = 123;
}, [])
const testClick = () => {
console.log(test.current) // undefined
}
return(<button onClick={testClick}>点击</button>)
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容