React.js useEffect 和依赖数组
教程代码,调用状态更改函数,强制渲染 (使用数组解构添加逗号)。
import React, { useEffect, useState } from "react";
const useAnyKeyToRender = () => {
const [ , forceRender ] = useState();
useEffect( () => {
window.addEventListener( "keydown", forceRender );
return () => window.removeEventListener( "keydown", forceRender );
}, [] );
};
export default function App() {
useAnyKeyToRender();
useEffect( () => {
console.log( "fresh render" );
} );
return <h1>Open the console</h1>;
}
在这个钩子(Hook)中我们不关心状态值。我们只需要状态函数:forceRender。
我了解数组解构的工作原理
const [fruit, setFruit] = useState('banana');
相当于
var fruitStateVariable = useState('banana'); // Returns a pair
var fruit = fruitStateVariable[0]; // First item in a pair
var setFruit = fruitStateVariable[1]; // Second item in a pair
我不明白这段代码是如何工作的
const [ , forceRender ] = useState();
为什么第一个数组元素是空白(忽略),为什么 forceRender 是第二个元素。
为什么不使用setForceRender?
forceRender 是如何调用的?
我理解这个钩子(Hook)的目标,但不知道依赖数组技巧。
如果我这样做:console.log(forceRender),出现:
ƒ bound dispatchAction() {}
<constructor>: "Function"
name: "Function"
我不明白这个钩子(Hook)是如何工作的,以及forceRender函数的机制。 看起来很简单,但我很困惑。
最佳答案
I couldn't seem to find any information online, so I am going to give you what I think is happening. I am not an expert, just someone who wants to provide his perspective. If anyone wants to correct me, please do!
让开这个:
让我们看一下这行代码:
// This isn't really useful but for the sake of this explanation
const [, setName] = useState("John")
useState
的返回语句看起来像这样:
function useState(initialState) {
// other code here
return [state, setState]
}
setState
位于索引 1
,我们请求将索引 1
分配给 setName
,并且忽略索引 0
。这就是我认为正在发生的事情。这可能是不正确的,或者由于没有很好地记录而不知道(我什至在 MDN 上找不到任何信息!),但这就是我认为正在发生的事情。
关于reactjs - React.js useEffect 和依赖数组,使用解构 useState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74952961/