简体   繁体   English

React JS - 如何在状态更新之前阻止渲染 [Hooks]

[英]React JS - How to prevent rendering before state being updated [Hooks]

I have a component which fetch data from an API to display some details to user:我有一个从 API 获取数据以向用户显示一些详细信息的组件:

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.但是当导航到达这个组件时,控制台显示错误无法访问 undefined 的名称,可能是因为状态尚未更新。

Is it right to check item and return null if it was not updated yet?如果尚未更新,检查项目并返回 null 是否正确? Something like this:像这样的东西:

if(!item) return null;

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

Or in that case should be better to use a class extended by React.Component and deal with its lifecycle properly?或者在那种情况下应该更好地使用由 React.Component 扩展的类并正确处理其生命周期?

You handle this in one of two ways:您可以通过以下两种方式之一处理此问题:

  1. Have the component render itself in a "loading" state, or让组件呈现“加载”状态,或

  2. Don't create the component until you have the data — eg, 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).在您拥有数据之前不要创建组件——例如,将 fetch 操作移动到其父级中,并且只有在父级拥有要呈现它的数据(您将其作为 props 传递)时才创建组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM