如何在ReactJS中的函数组件内部声明变量 [英] How to declare a variable inside a functionnal component in ReactJS

查看:56
本文介绍了如何在ReactJS中的函数组件内部声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量"myVar",(无州)

I have a variable "myVar" (NOT A STATE)

const myComponent = () => {
  const [myState, setMyState] = useState(true)
  const myVar = false

  return <button onClick={() => {myVar = true} >Click here</button>

}

在编写时,重新渲染组件时,然后重新初始化了 myVar ...我想让变量保持其先前的值.如何获得这种行为?

As it is written, when the component is re-rendered, then myVar is re-initialized... I want to have the variable keep its previous value. How can I get this behavior?

我发现的解决方案是:

解决方案1:在组件外部(但不在组件范围内)初始化变量

SOLUTION 1 : Initialise the variable outside of the component (but not in the component scope)

let myVar = 'initial value';
const myComponent = () => {
  ....
  // myVar is updated sometimes when some functions run
}

解决方案2:声明组件属性(但公开)

SOLUTION 2 : declare a component prop (but public)

const myComponent = ({myVar = true) => {
  ....
}

解决此问题的推荐方法是什么?

What is the recommended way to solve this problem?

推荐答案

反应文档建议使用

React docs suggest to use useRef to keep an arbitrary mutable value around. So, you could do this:

// set ref
const myValRef = React.useRef(true);

// ...

// update ref
myValRef.current = false;

这篇关于如何在ReactJS中的函数组件内部声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆