![](/img/trans.png)
[英]How to use react Hook state variables without a callback function?
[英]How to use map function on react state hook
有人可以解釋一下,為什么我不能在React狀態鈎子上運行JavaScript map函數?
const [sequenceNames, setSequenceNames] = useState(null);
useEffect(() => {
fetch('/savedFiles')
.then(response => response.json())
.then(data => setSequenceNames(data));
}, []);
const table = sequenceNames.map(name => Sequence(name));
這適用於for循環,但是我的linter禁止使用in 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
數組不應為null。
您遇到的問題是您將sequenceNames
的初始狀態設置為null
,因此您遇到了競爭條件,第一次嘗試在sequenceNames
運行循環時,它為null
。 你可以將sequenceNames
初始化為一個空數組[]
,但實現你想做的事情的最好方法是擁抱鈎子。
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>;
}
更改
const table = sequenceNames.map(name => Sequence(name));
至
const table = Array.isArray(sequenceNames) && sequenceNames.map(name => Sequence(name));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.