React JS-如何在状态更新前防止渲染[Hooks] [英] React JS - How to prevent rendering before state being updated [Hooks]

查看:102
本文介绍了React JS-如何在状态更新前防止渲染[Hooks]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,可以从API提取数据以向用户显示一些详细信息:

I have a component which fetch data from an API to display some details to user:

const ItemDetail = ({match}) => {
    const [item, setItem] = useState(null);

    useEffect(() => {
        const abort = new AbortController();
        fetchItem(abort);

        return function cleanUp(){
            abort.abort();
        }
    },[]);

    const fetchItem = async (abort) => {
        const data = await fetch(`https://fortnite-api.theapinetwork.com/item/get?id=${match.params.id}`, {
            signal: abort.signal
        });

        const fetchedItem = await data.json();
        setItem(fetchedItem.data.item);
    }

    return (
        <h1 className="title">{item.name}</h1>
    );
}

export default ItemDetail;

但是,当导航到达此组件时,控制台会显示错误无法访问未定义的名称,可能是因为状态尚未更新.

But when navigation reachs this component, the console shows the error Cannot access name of undefined, probably because the state was not updated yet.

检查项目是否正确,如果尚未更新,则返回null?像这样:

Is it right to check item and return null if it was not updated yet? Something like this:

if(!item) return null;

return (
        <h1 className="title">{item.name}</h1>
);

或者在那种情况下,最好使用React.Component扩展的类并正确处理其生命周期?

Or in that case should be better to use a class extended by React.Component and deal with its lifecycle properly?

推荐答案

您可以通过以下两种方式之一进行处理:

You handle this in one of two ways:

  1. 让组件以正在加载"状态呈现自己,或者

  1. Have the component render itself in a "loading" state, or

在拥有数据之前不要创建组件.例如,将抓取操作移到其父级中,并且只有在父级具有要呈现的数据(您将其作为道具传递)后,才创建该组件.

Don't create the component until you have the data — e.g., move the fetch operation into its parent, and only create the component once the parent has the data to render it (which you pass as props).

这篇关于React JS-如何在状态更新前防止渲染[Hooks]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆