【发布时间】:2021-10-30 05:07:11
【问题描述】:
我正在从我的“后端”CMS 获取数据 - 一切正常,但是当我想设置默认值时,我收到未定义数据的错误。
我的内容分为一些类别,例如
const [category1, setCategory1] = useState([]);
const [category2, setCategory2] = useState([]);
然后我从后端获取数据
useEffect(() => {
const fetchData = async () => {
const result = await client.query(
Prismic.Predicates.at('document.type', 'post'),
{ pageSize: 100 }
);
if (result) {
const category1Arr = [];
const category2Arr = [];
result.results.forEach((post) => {
switch (post.data.category[0].text) {
case 'Category1':
category1Arr.push(post);
break;
case 'Category2':
category2Arr.push(post);
break;
default:
console.warn('Missing blog post category.');
}
});
setCategory1(category1Arr);
setCategory2(category2Arr);
return setDocData(result);
} else {
console.warn(
'Not found'
);
}
};
fetchData();
}, []);
上面的代码没有任何问题,但是选择的类别应该默认打开一个帖子。
当您可以选择类别时,我有菜单,因此我使用activeComponent 功能。
const [activeComponent, setActiveComponent] = useState('category1');
const modifyActiveComponent = React.useCallback(
(newActiveComponent) => {
setActiveComponent(newActiveComponent);
},
[setActiveComponent]
);
所以 category1 默认是激活的,因此该类别也应该有默认帖子。
这是我尝试过的:
const [postTitle, setPostTitle] = useState('');
const [postText, setPostText] = useState([]);
{activeComponent === 'category1' &&
category1.length > 0 && category1.map((post) => {
return ( <button onClick={()=> {setPostTitle(post.data.title[0].text); setPostText(post.data.body)}}
数据显示为典型的{postTitle} 和{postText}
我试图像这样在每个类别中放置默认值
useEffect(() => {
if (activeComponent === 'category1') {
setPostTitle(category1[2].data.title[0].text);
setPostText(category1[2].data.body);
}
if (activeComponent === 'category2') {
// same here just with category2 }
}, [activeComponent, category1, category2]);
但上面的代码给了我一个错误或未定义的数据,即使它应该是正确的。
如何使用上述逻辑创建默认值?一切都像魅力一样,只是默认数据不起作用:(
这是对象数组:
【问题讨论】:
-
你得到的错误是什么?
-
所以如果我这样做
setPostTitle(category1[2].data.title[0].text)它会给我 TypeError: Cannot read property 'data' of undefined, 即使标题的路径是正确的。 -
有可能在第一次渲染中,
data未填充,而在第二次或第三次渲染中,您已设法在上述逻辑中填充数据,值已填充向上。您可以使用console.log和调试器检查是否是这种情况? -
如果我
console.log只是 category1 它会打印出我的帖子数组,但是当我尝试 console.log 更深的路径时,它不起作用。有趣的是它与category1[2].id一起使用 - 它打印正确的 id,但与 .data 它不起作用。 -
你的
console.log打印data对象吗?
标签: javascript reactjs api react-hooks fetch