React网站如何显示accountInfo[4]的值并解决undefined属性读取报错
问题原因
- 类型不匹配:useAccountInfo的初始状态是
BigNumber.from(0)(数值类型对象),和后续接口返回的数组类型不一致,初始渲染时访问[4]属性自然不存在 - 异步加载时序问题:
fetchAccountInfo是异步请求,组件第一次渲染时请求还未完成,拿到的是初始值而非接口返回的数组 - 代码逻辑错误:Hero组件中
const setPaid = console.log(accountInfo)写法错误,console.log返回值为undefined,相当于直接把undefined传给了Value组件 - 缺少边界判断:未判断钱包是否连接、accountInfo是否为有效数组、数组长度是否≥5的情况,直接取下标会抛出异常
修改方案
1. 调整useAccountInfo.js代码
将初始值和返回值类型统一为数组,避免类型错乱:
import { useEffect, useState } from 'react' import { useWallet } from 'use-wallet' import { BigNumber } from 'ethers'; import useBlock from './useBlock' import useTokenInfo from './useTokenInfo'; const useAccountInfo = () => { // 初始值改为空数组,和后续接口返回的数组类型匹配 const [accountInfo, setAccountInfo] = useState([]); const {account, ethereum} = useWallet(); const block = useBlock(); const tokenInfo = useTokenInfo(); const fetchAccountInfo = async () => { if (!account || !tokenInfo?.accountInfo) { setAccountInfo([]); return; } const res = await tokenInfo.accountInfo(); setAccountInfo(res || []); }; useEffect(() => { fetchAccountInfo(); }, [block, account, ethereum, tokenInfo]); return accountInfo; } export default useAccountInfo;
2. 调整Hero组件代码
修正逻辑错误,添加边界判断,使用可选链安全取值:
import React from 'react'; import useAccountInfo from '../abi/useAccountInfo'; import Value from '../utils/value'; const Hero = () => { const accountInfo = useAccountInfo(); // 用可选链安全取accountInfo[4],不存在时返回undefined const paidValue = accountInfo?.[4]; return ( <div> {/* 可自定义加载状态,避免空白显示 */} {paidValue ? <Value value={paidValue}/> : <span>加载中...</span>} </div> ); } export default Hero;
内容的提问来源于stack exchange,提问作者jhaz
相关产品推荐
相关产品推荐

