无法读取未定义的属性(读取“小”)

Cannot read properties of undefined (reading "small')

在我的 React 项目中,我得到 api 并将数据存储在状态中。

const [infor,setInfor] = useState({}); //these is my hook for store data
const [chartdata,setChartdata] = useState([]);

useEffect(()=>{
    const setter = async()=>{
        const dd = await(info());
        setInfor(dd.data);
        console.log(dd.data);
        const dd2 = await(chart());
        setChartdata(dd2);
    }
    setter();
},[])

它工作正常并且存储数据非常好。我将数据存储在 (infor) 我想在反应组件中使用该数据,所以写这些代码

    return (
    <div id={style.main}>
        {
        !infor ? <img src={spinner} /> : //these code checking infor isn't null
        <span className={style.info}>
            <img src={infor.image.small}  title={infor.id} className={style.icon} />
            <p>{infor.market_cap_rank}</p>
            <p>{infor.name}</p>

            
        </span>
        }
    </div>
);

这些是我需要的数据

一切似乎都很好,但这是一个错误

在您的编译器搜索 infor.image 时的第一个渲染中,它变得未定义,因此抛出错误。要么使用 put 检查,就像检查 infor 存在一样,然后图像存在,然后小存在。它可以通过使用 infor?.image?.small 来完成。但这样做的问题是你会在屏幕上得到 undefined 。您必须牢记这一点以正确地进行检查,例如 infor?.image?.small ? infor.image.small : ''.

!infor ? <img src={spinner} /> : /**/

在上面的行中,!infor 将始终为真,因为 !{} 为真。 有两种方法可以解决您的问题。

  1. 初始化infornull

    const [infor,setInfor] = useState(null);

  2. 使用Object.keys()验证对象

    !Object.keys(infor).length ? <img src={spinner} /> : /***/