React项目出现Cannot read properties of undefined(reading 'toString')错误
问题解决:TypeError: Cannot read properties of undefined (reading 'toString')
问题原因
你没直接调用toString,但Ant Design的Statistic组件内部会对传入的value执行toString做格式化处理。当globalStats的某个属性(比如totalExchanges、totalMarketCap等)为undefined时,传给Statistic的value就会是undefined,组件内部处理时就会触发这个错误。
虽然你用了isFetching判断加载状态,但存在请求完成后data?.data?.stats依然为undefined的情况,这时渲染Row里的Statistic组件就会报错。
解决方案
有两种可行的修复方式:
1. 给Statistic的value设置默认值
给每个可能为undefined的属性添加默认值,避免传入undefined给Statistic:
<Row> <Col span={12}> <Statistic title='Total Cryptocurrencies' value={globalStats?.total || 0} /> </Col> <Col span={12}> <Statistic title='Total Exchanges' value={millify(globalStats?.totalExchanges || 0)} /> </Col> <Col span={12}> <Statistic title='Total Market Cap' value={millify(globalStats?.totalMarketCap || 0)} /> </Col> <Col span={12}> <Statistic title='Total 24h Volume' value={millify(globalStats?.total24hVolume || 0)} /> </Col> <Col span={12}> <Statistic title='Total Markets' value={millify(globalStats?.totalMarkets || 0)} /> </Col> </Row>
2. 条件渲染Row组件
确保globalStats存在后再渲染Row,避免数据未就绪时渲染统计组件:
{globalStats && ( <Row> <Col span={12}> <Statistic title='Total Cryptocurrencies' value={globalStats.total} /> </Col> <Col span={12}> <Statistic title='Total Exchanges' value={millify(globalStats.totalExchanges)} /> </Col> <Col span={12}> <Statistic title='Total Market Cap' value={millify(globalStats.totalMarketCap)} /> </Col> <Col span={12}> <Statistic title='Total 24h Volume' value={millify(globalStats.total24hVolume)} /> </Col> <Col span={12}> <Statistic title='Total Markets' value={millify(globalStats.totalMarkets)} /> </Col> </Row> )}
内容的提问来源于stack exchange,提问作者amirhossein
相关产品推荐
相关产品推荐

