gpt4 book ai didi

javascript - 如何在react状态钩子(Hook)上使用map函数

转载 作者:行者123 更新时间:2023-11-30 09:18:09 29 4
gpt4 key购买 nike

有人可以解释一下,为什么我无法在 React 状态 Hook 上运行 JavaScript 映射函数?

const [sequenceNames, setSequenceNames] = useState(null);

useEffect(() => {
fetch('/savedFiles')
.then(response => response.json())
.then(data => setSequenceNames(data));
}, []);

const table = sequenceNames.map(name => Sequence(name));

这适用于 for in 循环,但我的 linter 禁止使用 for in。

const table = [];

for (const name in sequenceNames) {
table.push(Sequence(sequenceNames[name]));
}

当我使用 .map 时,我收到以下错误。

TypeError: Cannot read property 'map' of null
at main.a21158832f7ed8c55e25.bundle.js:1
at Bi (main.a21158832f7ed8c55e25.bundle.js:1)
at main.a21158832f7ed8c55e25.bundle.js:1
at f (main.a21158832f7ed8c55e25.bundle.js:1)
at d (main.a21158832f7ed8c55e25.bundle.js:1)
at main.a21158832f7ed8c55e25.bundle.js:1

即使我的sequenceNames数组不应该为空。

最佳答案

您遇到的问题是您正在设置 sequenceNames null 的初始状态,因此您遇到了竞争条件,第一次尝试时在 sequenceNames 上运行循环,它是 null。您可以将 sequenceNames 初始化为空数组 [],但完成您想要做的事情的最佳方法是采用钩子(Hook)。

import React, { useMemo, useState } from 'react';
import { Sequence } from '.';

export interface DisplayNamesProps {
id?: number;
}

export function DisplayNames(props: DisplayNamesProps) {
const { id } = props;
const [sequenceNames, setSequenceNames] = useState<Sequence[]>([]);

// Use useEffect with the 2nd param, to guard against `fetch`
// executing on each render. In this example I use `id` as
// a var that should be unique for each `fetch` call.
useEffect(() => {
fetch(`/savedFiles/${id}`)
.then(response => response.json())
.then(data => setSequenceNames(data));
}, [id]);

// Create a memoized var `table` that updates when there
// is a change to `sequenceNames`.
const table = useMemo(() => {
return sequenceNames.map(name => Sequence(name))
}, [sequenceNames]);

return <div>{table}</div>;
}

关于javascript - 如何在react状态钩子(Hook)上使用map函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53569616/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com