请解决此错误 - 未捕获的 TypeError:无法读取未定义的属性(读取“映射”)

Please solve this error - Uncaught TypeError: Cannot read properties of undefined (reading 'map')

提问人:Ashley Ferns 提问时间:11/15/2022 更新时间:11/15/2022 访问量:1306

问:

react-refresh-runtime.development.js:315 未捕获的 TypeError:无法读取 undefined 的属性(读取“map”)

const Exchange = () => {
  const { exchanges, setExchanges } = useState([]);
  const { loading, setLoading } = useState(true);

  useEffect(() => {
    const fetchExchanges = async () => {
      const { data } = await axios.get(`${server}/exchanges`);
      // console.log(data);
      setExchanges(data);
      setLoading(false);
    };
    fetchExchanges();
  });
  return (
    <Container maxW={"container.xl"}>{loading ? ( <Loader /> ): (<>
        <HStack>
            {exchanges.map((i) => 
             (
                    <div>{i.name}</div>
                ))}
        </HStack>
    </>)}
    </Container>
  );
};
javascript reactjs 反应钩子

评论

1赞 junwen-k 11/15/2022
setExchanges(data);可能是导致问题的原因。请您的数据,确保它是一个数组。console.log

答:

1赞 Ahmet Ulutaş 11/15/2022 #1

您正在尝试呈现异步获取的交换。因此,当代码开始执行块时,它是空的。你不能映射一个空数组并 i.name 出来。尝试通过添加可选链接来等待它被 axios 调用填充。exchanges.map

exchanges?.map((i) =>  .........

评论

0赞 Nidhi Dadiya 11/15/2022
或者你也可以做一些类似的事情exchanges.length > 0 && exchanges.map()
0赞 11/15/2022
这是错误的。你绝对可以在一个空数组上调用 .map(),这就是为什么最好将状态初始化为 [] 而不是 null/undefined(假设它是一个数组)。此外,因为它是空的,.map() 永远不会迭代,因此 i.name 永远不会被调用。所以这也不可能是问题所在。问题是状态从错误的 GET 响应中设置为 undefined,因此没有问题的初始 [] 状态被 undefined 覆盖。这里的解决方案是调试并添加对GET响应的错误检查。
2赞 Ashley Ferns 11/15/2022 #2

而不是

const { exchanges, setExchanges } = useState([]);
  const { loading, setLoading } = useState(true);

  const [ exchanges, setExchanges ] = useState([]);
  const [ loading, setLoading ] = useState(true);