【问题标题】:How to use map function on react state hook如何在反应状态挂钩上使用地图功能
【发布时间】:2019-05-03 07:44:09
【问题描述】:

谁能解释一下,为什么我不能在 React 状态钩子上运行 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 数组不应该为空。

【问题讨论】:

    标签: javascript reactjs for-loop


    【解决方案1】:

    您遇到的问题是您正在设置sequenceNames null 的初始状态,因此您遇到了竞争条件,第一次尝试在sequenceNames 上运行循环时,它是@ 987654324@。您可以将 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>;
    }
    

    【讨论】:

      【解决方案2】:

      改变

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

      到

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

      【讨论】:

      • 不客气。无论您使用哪个反应版本,解决方案都保持不变
      猜你喜欢
      • 2021-10-02
      • 2021-05-19
      • 2021-06-22
      • 2021-07-19
      • 2020-04-04
      • 2021-10-17
      • 1970-01-01
      • 2022-09-26
      • 1970-01-01
      相关资源
      最近更新 更多