简体   繁体   English

如何根据本地存储中是否有数据有条件地渲染这个组件?

[英]How can I conditionally render this component based on whether or not there is data in localstorage?

I want MyList to render whatever is in localStorage (works great), however when there is nothing in local storage and I render the component, it renders empty.我希望 MyList 呈现 localStorage 中的任何内容(效果很好),但是当本地存储中没有任何内容并且我呈现组件时,它呈现为空。 I would like to have a placeholder there for when that occurs.当发生这种情况时,我想在那里有一个占位符。 How can I best do that?我怎样才能最好地做到这一点?

const MyList = ({setDrinks}) => {
    const setMyList = () => {
        let parsedData = JSON.parse(localStorage.getItem('favoriteDrinks'))
        setDrinks(parsedData)
    }

    return (
        <div>
            <button className="my-list" onClick={setMyList}>My List</button>
        </div>
    )
}

export default MyList

You can assign a random placeholder if your localStorage does not have data.如果您的localStorage没有数据,您可以分配一个随机占位符。 Here's a minimal solution:这是一个最小的解决方案:

const MyList = ({setDrinks}) => {
    const setMyList = () => {
        const myDrinks = localStorage.getItem('favoriteDrinks');
        if (!myDrinks) {
            setDrinks({ message: "No drinks found!" });
            return;
        } 
        let parsedData = JSON.parse(myDrinks);
        setDrinks(parsedData);
    }

    return (
        <div>
            <button className="my-list" onClick={setMyList}>My List</button>
        </div>
    )
}

export default MyList 

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

相关问题 根据 localStorage 有条件地渲染组件 - Conditionally render component depending on localStorage 如何根据特定页面有条件地呈现 Gatsby 中的组件? - How do I conditionally render a component in Gatsby based on specific page? 如何根据 prop 有条件地渲染组件的颜色? - How do I conditionally render the color of my component based on the prop? 根据功能组件中的数据有条件地渲染元素 - Conditionally render elements based on data in functional component 如何根据当前是否选择元素来有条件地切换元素 - How can I conditionally toggle elements based on whether or not they are currently selected 如何在组件渲染之前基于 localstorage 操作组件 state - how to manipulate component state based on localstorage before component render 如何有条件地渲染功能组件中的项目? - How can conditionally render items in functional component? 如何在 React 中的对象数组上 map,然后根据先前的值有条件地渲染组件? - How do I map over an array of objects in React and then conditionally render a component based on a previous value? 有条件地在组件中呈现 Firebase 数据 - Conditionally render firebase data in component React,根据localStorage变化渲染组件 - React, render component based on localStorage changes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM