首页  >  问答  >  正文

在尝试设置用于显示在图表上的数据时,React .map不起作用

<p>我想在图表上显示来自API的数据,我知道如何做,但在使用.map函数时出现错误。我想将prices[0]和prices[1]分开,以便可以访问它们,因为我的响应看起来像这样:</p> <pre class="brush:php;toolbar:false;">"prices": [ [ 1689598842536, 30208.47 ], [ 1689602431443, 30274.72 ],</pre> <p>这是带有.map函数的代码:</p> <pre class="brush:php;toolbar:false;">const params = useParams() const [coin, setCoin] = useState({}) const [chart, setChart] = useState({}) const [loading, setLoading] = useState(false) const chartUrl = `https://api.coingecko.com/api/v3/coins/${params.coinId}/market_chart?vs_currency=usd&days=30&precision=2` const url = `https://api.coingecko.com/api/v3/coins/${params.coinId}` useEffect(() => { axios.get(url).then((res) => { setCoin(res.data) setLoading(true) }).catch((error) => { console.log(error) }) axios.get(chartUrl).then((res) => { setChart(res) }).catch((error) => { console.log(error) }) }, []) const coinChartData = chart.prices.map(value => ({x: value[0], y: value[1]}))</pre> <p>我在最后一行得到了错误 <code>Cannot read properties of undefined (reading 'map')</code></p> <p>我尝试将coinChartData放在useEffect内部,它可以工作,但我无法在useEffect函数之外使用coinChartData。</p>
P粉277464743P粉277464743430 天前497

全部回复(1)我来回复

  • P粉133321839

    P粉1333218392023-08-18 00:07:47

    初始值为chart的是一个空对象:

    const [chart, setChart] = useState({})

    该对象没有prices属性,所以正如错误所述,chart.pricesundefined

    你可以将该属性初始化为空数组:

    const [chart, setChart] = useState({ prices: [] })

    或者在访问可能为undefined的属性时使用可选链:

    const coinChartData = chart.prices?.map(value => ({x: value[0], y: value[1]}))

    根据最终使用数据的位置/方式,您可能还有其他选项。但无论如何,如果对象可能没有prices属性,那么您不能总是使用该属性。您需要确保该属性始终存在,或者在尝试使用之前以某种方式有条件地检查它是否存在。

    回复
    0
  • 取消回复