我可以在 reactstrap 的渲染中使用在 useEffect 中声明的变量吗?
Can I use the variables declared in useEffect inside of my render in reactstrap?
我的导航栏中有一个 useEffect 挂钩:
const spoon = localStorage.getItem("true");
useEffect(() => {
console.log(spoon")
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', `https://server.com/${spoon}`, false);
xmlHttp.setRequestHeader('AO', `Password ${PASS}`)
xmlHttp.send()
console.log(xmlHttp.response)
var data = JSON.parse(xmlHttp.response);
console.log(data["user"]["avatar"])
}, []);
现在,当用户登录时,我会在导航栏中触发请求以检索用户头像,但是,我只想执行一次,所以我使用 useEffect
就好像我不这样做一样,在两者之间导航页面变慢,因为每次点击将用户带到新页面都会触发导航栏中的另一个 http get 请求。
现在 useEffect 确实起作用了,除了现在我认为无法在范围之外使用 data
变量(?),这意味着在导航栏渲染中我无法渲染用户头像。有没有解决的办法?或者我可以在渲染中使用在 useEffects 中声明的变量吗?这是我的导航栏渲染代码片段:
return (
...
<DropdownToggle
caret
color="default"
nav
onClick={(e) => e.preventDefault()}
>
<div className="photo">
<img
alt="..."
src='{data["user"]["avatar"]}' /*<-I need the data variable here so I can get the users avatar
from request*/
/>
</div>
<b className="caret d-none d-lg-block d-xl-block" />
<p className="d-lg-none">Log out</p>
</DropdownToggle>
)
您不能在渲染中使用 useEffect 中的变量。如果你想使用 useEffect
中的东西,你有两个选择:
- 为数据创建状态,即
useState
但是,如果您需要的话,这将触发重新渲染。
- 使用引用,即
useRef()
这可用于拥有一个在整个渲染过程中持久存在的变量。但是,对 ref 的更改不会触发重新渲染,请参阅:https://reactjs.org/docs/hooks-reference.html#useref
鉴于您正在 src
中使用数据,您将必须使用状态来允许更改数据以重新呈现组件。
我的导航栏中有一个 useEffect 挂钩:
const spoon = localStorage.getItem("true");
useEffect(() => {
console.log(spoon")
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('GET', `https://server.com/${spoon}`, false);
xmlHttp.setRequestHeader('AO', `Password ${PASS}`)
xmlHttp.send()
console.log(xmlHttp.response)
var data = JSON.parse(xmlHttp.response);
console.log(data["user"]["avatar"])
}, []);
现在,当用户登录时,我会在导航栏中触发请求以检索用户头像,但是,我只想执行一次,所以我使用 useEffect
就好像我不这样做一样,在两者之间导航页面变慢,因为每次点击将用户带到新页面都会触发导航栏中的另一个 http get 请求。
现在 useEffect 确实起作用了,除了现在我认为无法在范围之外使用 data
变量(?),这意味着在导航栏渲染中我无法渲染用户头像。有没有解决的办法?或者我可以在渲染中使用在 useEffects 中声明的变量吗?这是我的导航栏渲染代码片段:
return (
...
<DropdownToggle
caret
color="default"
nav
onClick={(e) => e.preventDefault()}
>
<div className="photo">
<img
alt="..."
src='{data["user"]["avatar"]}' /*<-I need the data variable here so I can get the users avatar
from request*/
/>
</div>
<b className="caret d-none d-lg-block d-xl-block" />
<p className="d-lg-none">Log out</p>
</DropdownToggle>
)
您不能在渲染中使用 useEffect 中的变量。如果你想使用 useEffect
中的东西,你有两个选择:
- 为数据创建状态,即
useState
但是,如果您需要的话,这将触发重新渲染。 - 使用引用,即
useRef()
这可用于拥有一个在整个渲染过程中持久存在的变量。但是,对 ref 的更改不会触发重新渲染,请参阅:https://reactjs.org/docs/hooks-reference.html#useref
鉴于您正在 src
中使用数据,您将必须使用状态来允许更改数据以重新呈现组件。