【问题标题】:How to setup default value of fetched data如何设置获取数据的默认值
【发布时间】: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


【解决方案1】:

在您的最后一段代码中,您有一个错字,这里:

useEffect(() => {
        if (activeComponent === 'category1') {
            setPostTitle(category1[2].data.title[0].text);
            setPostText(category[2].data.body);
        }
        if (activeComponent === 'category2') {
            // same here just with category2        }
    }, [activeComponent, category1, category2]);

应该是:

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]);

在第一个if 语句中,在第二个setPostText 中,你有category 而不是category1

【讨论】:

  • OP 评论说他们对setPostTitle 也有问题
  • 谢谢@Arpit,但这不是问题,它只是这里的错字,在我的代码中,真实的类别名称是正确的。
  • hmm... 如果是这种情况,那么您在尝试访问data 对象时一定存在一些逻辑错误,您应该按照@SamridhTuladhar 的建议进行一些调试
猜你喜欢
  • 1970-01-01
  • 2021-12-22
  • 2015-02-20
  • 1970-01-01
  • 2018-11-08
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
相关资源
最近更新 更多