使用useState初始化cryptoInfo后,替换为cryptoInfo?.map出现undefined问题
问题原因及解决办法
这不是useState的使用错误,而是你没搞清楚useState初始值的执行规则:useState的初始值只会在组件首次渲染时执行一次。
具体原因
组件第一次渲染时,useGetCryptosQuery还在请求数据,此时cryptoList是undefined,所以cryptoInfo的初始值就是undefined。等请求完成后,cryptoList更新成有数据的状态,但useState不会自动重新执行初始化逻辑,cryptoInfo依然是之前的undefined,所以用cryptoInfo?.map会得到undefined。
解决办法
分两种情况处理:
不需要修改数据的情况
如果只是展示数据,根本没必要把cryptoList?.data?.coins存到state里,直接用cryptoList?.data?.coins?.map就行,就像你原来的代码那样。需要修改数据的情况
如果后续要对数据做修改(比如筛选、排序),必须存到state里的话,要加useEffect监听cryptoList的变化,当数据返回时手动更新cryptoInfo:
import { useEffect } from 'react'; const Cryptocurrencies = ({ simplified }) => { let count = simplified ? 10 : 100; const { data: cryptoList, isFetching } = useGetCryptosQuery(count); const [cryptoInfo, setCryptoInfo] = useState([]); // 初始值设为空数组更稳妥 useEffect(() => { // 当cryptoList有数据时,更新state if (cryptoList?.data?.coins) { setCryptoInfo(cryptoList.data.coins); } }, [cryptoList]); // 依赖项设为cryptoList,数据变化时触发 console.log(cryptoInfo); if (isFetching) return "Loading..."; return ( <> <Row gutter={[16, 16]} className="crypto-card-container"> {cryptoInfo?.map((currency) => ( <Col xs={24} sm={12} xl={6} className="crypto-card" key={currency.uuid} > {/* 组件内容 */} </Col> ))} </Row> </> ); }; export default Cryptocurrencies;
内容的提问来源于stack exchange,提问作者Raaghav Manivel
相关产品推荐
相关产品推荐

