开发者问题收集

请解决此错误 - 未捕获的类型错误:无法读取未定义的属性(读取‘map’)

2022-11-15
1393

react-refresh-runtime.development.js:315 未捕获 TypeError:无法读取未定义的属性(读取“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>
  );
};
2个回答

而不是

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

这个

const [ exchanges, setExchanges ] = useState([]);
  const [ loading, setLoading ] = useState(true);
Ashley Ferns
2022-11-15

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

exchanges?.map((i) =>  .........
Ahmet Ulutaş
2022-11-15