React useState 似乎不接受这里的默认值?

Meh*_*far 8 arrays typescript reactjs react-hooks

我有一个图表组件,可以在其中显示/隐藏特定的线条。为了跟踪哪些行是活动的,我将activeKeys数组保持在一个状态。最初,我从一个getKeys接受数据数组的函数中获取键名。

当我这样做时:

    const defaultValue = getKeys(data)
    console.log('defaultValue from keys', defaultValue)
    const [activeKeys, setActiveKeys] = useState(defaultValue)
    console.log('activeKeys', activeKeys)
Run Code Online (Sandbox Code Playgroud)

第一个控制台日志显示正确的键:

["createdCount", "confirmedCount", "hasFeedbackCount"]
Run Code Online (Sandbox Code Playgroud)

第二个控制台日志显示 []

如果我这样做:

const defaultValue = ["createdCount", "confirmedCount","hasFeedbackCount"]
console.log('defaultValue', defaultValue)
const [activeKeys, setActiveKeys] = useState(defaultValue)
console.log('activeKeys', activeKeys)
Run Code Online (Sandbox Code Playgroud)

第一个控制台日志显示相同的数组:

["createdCount", "confirmedCount", "hasFeedbackCount"]
Run Code Online (Sandbox Code Playgroud)

activeKeys显示正确的数组:

["createdCount", "confirmedCount", "hasFeedbackCount"]
Run Code Online (Sandbox Code Playgroud)

useState坏了还是什么?BygetKeys是一个简单的功能,没有承诺或类似的东西。它看起来像这样:

["createdCount", "confirmedCount", "hasFeedbackCount"]
Run Code Online (Sandbox Code Playgroud)

的形状Props['data']是:

["createdCount", "confirmedCount", "hasFeedbackCount"]
Run Code Online (Sandbox Code Playgroud)

And*_*son 4

我也有同样的问题。确实没有错误React.useState

这里的问题是您的组件正在安装并计算空数组作为默认值。随后,您的“默认值”将更改为您预期的默认值,但React.useState已经有一个空数组的默认值。

要解决此问题,您需要避免安装组件,直到所需的默认值可用。或者,您可以执行类似使用React.useEffect钩子来查找 props 中的更改并调用输出的 setter(数组中的第二项)之类的操作React.useState