【问题标题】:Variable can't be used in useEffect Hook变量不能用于 useEffect Hook
【发布时间】:2020-08-19 09:34:08
【问题描述】:

为什么会出现这个错误:

'height' 已声明,但它的值永远不会被读取。ts(6133)

useEffect(() => {
   let height = contentDiv.current ? contentDiv.current.scrollHeight : 0;
   let test = (height: number) => height;
   setExpandedHeight(test);
  }, [children]
);

我错过了什么吗?为什么useEffect里面的函数不能使用变量?

【问题讨论】:

  • 好吧,写错了。你从未使用过你声明的height
  • useEffect 回调中的局部变量被它的参数隐藏在测试函数内部 - 这就是你想要的吗?

标签: javascript reactjs variables scope react-hooks


【解决方案1】:

这是一个箭头函数

let test = (height: number) => height;

它接受一个参数并返回它,它不使用你的变量,你可以做类似的事情

useEffect(() => {
  let height = contentDiv.current ? contentDiv.current.scrollHeight : 0;
  let test = (height: number) => height;
  setExpandedHeight(test(height));
}, [children]);

但它不会真的有用

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 2021-07-04
    • 2019-10-08
    • 2021-08-02
    • 1970-01-01
    • 2020-10-22
    • 2021-03-11
    • 2021-02-23
    • 2021-12-23
    相关资源
    最近更新 更多