简体   繁体   中英

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:

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.

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

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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