定义了一个数据:
const [news, setNews] = useState({});
在useEffect中赋值:
axios.get(`http://localhost:8000/news/${id}?_expand=category`).then(
(res) => {
console.log(res.data);
setNews(res.data);
setsubTitle(res.data.category.title);
},
(err) => {
console.log(err);
}
);
在结构中使用:
subTitle={news.category.title}
此时会在执行useEffect之前报错:
Uncaught TypeError: Cannot read properties of undefined (reading 'title')
发现无法读取第二层的title属性。这是因为页面会在数据返回前渲染一次,此时数据还没有返回,news中没有category字段。
解决方法:
1.有数据之后再读取。这样需要给每个用到深藏数据的地方都加上问号
subTitle={news.category?.title}
2.有数据返回之后再渲染
{news && 结构代码}