持久化数据反应

时间:2021-04-15 10:34:50

标签: javascript reactjs react-hooks

我的仪表板应用出现问题。本质上,新闻标签将呈现源自 API 并通过上下文传输的信息

然后我使用本地存储保存数据并在每个选项卡中访问它。问题是,尽管将它持久化在本地存储中并使用它设置状态,但每次刷新都会引发错误

基本上,一旦我刷新或更改任何代码,react 就会丢失数据(但它仍然记录它在那里?) 然后访问的错误是:

“无法访问 articled[0].topic 的值” - 基本上是说它不存在或为空

function DashBoard({name, userOptions, location, country}) {

    const news = useContext(GlobalContext)
    const [article, setArticle] = useState(null) 

    useEffect(()=> {
        setArticle(news)
        console.log(article)
        localStorage.setItem('news', JSON.stringify(news))
    },[])

    useEffect(()=> {
        const data = localStorage.getItem('news')
        setArticle(JSON.parse(data))
        console.log(article[0].topic)
    },[])
    
const generateTabs = (topic, article)=> {
    
    return  <Tab tabType = 'tab' className ='nws-container-mid' topic = {topic} article = {article} />
           
}

     
   

    return (
        <div className ="wrapper">
        
     
        <div className="container__Dash">
                <Header name = {name}/>


                <div className ="container__new">
                    
                    <div className ="container__tab surface"> 
                        <FeaturedNews  userOptions = {userOptions} country = {country} />
                        <PictureOfTheDay userOptions = {userOptions} />
                    </div>
                    <div className ="container__tab middle"> 
                        {console.log()}

                       {generateTabs(article[0].topic)}
                       {generateTabs(article[1].topic)}
                       {generateTabs(article[2].topic)}
                        
 
                    </div> 
                   
                       <div className ="container__tab footer">

                       {generateTabs(article[3].topic)}
                       {generateTabs(article[4].topic)}

                        <Settings />
                        <Weather location = {location} country = {country}/>
                    </div>
                </div>
            </div>
    </div>
    )
}

export default DashBoard;

如何让它始终读取提供的数据?或者我怎样才能让它在每个选项卡中呈现之前等待数据?

0 个答案:

没有答案