【问题标题】:Cannot read property of undefined React js无法读取未定义的 React js 的属性
【发布时间】:2021-07-12 09:09:59
【问题描述】:

所以我有来自 API 的数据,要在选项卡组件中呈现...一个接受来自 api 的数据并将其呈现在组件中的函数

问题是,数据不是持久的,尽管我将它存储在 Localstorage 中, 因此,当我调用 generateTabs 方法并在下面的代码中放置参数时,它会引发错误 - 无法读取未定义的属性“主题”

有没有办法让它根据数据有条件地呈现? 还是在读取参数之前等待数据? 也许让它异步?

问题摘要:

数据来自 API -- 使用函数访问(作为 props 传递给组件的参数) -- 存储在 localStorage -- setState from localStorage -- 刷新页面 -- 无法读取未定义的属性“主题”

我希望它在在选项卡中呈现之前等待数据...所以持久化不是一个理想的解决方案

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

    useEffect(()=> {
        const data = localStorage.getItem('news')
        const mainData = JSON.parse(data)
        setArticle(mainData)
        console.log(article)
        
    },[])
    
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(article[0].topic)} */}

                       {generateTabs((article[0].topic))}
                       {generateTabs()}
                       {generateTabs()}
                       <button onClick={openModal}>Set Modal </button>
                       <Modal showModal={showModal} setModal = {setModal} > </Modal>
                        
 
                    </div> 
                   
                       <div className ="container__tab footer">

                       {generateTabs()}
                       {generateTabs()}

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

export default DashBoard


【问题讨论】:

    标签: javascript reactjs local-storage state


    【解决方案1】:

    useEffect() 在渲染之后执行。因此,对于您的第一次渲染,它会渲染包装器 div 并尝试读取 article[0].topic)),但尚未设置文章状态,这就是发生错误的原因。

    为了防止错误,使用

     {article.length!==0 && generateTabs(article[0].topic,article[0].article)}
    

    generateTabs 函数只有在文章数组不为空时才会被调用。

    另外,{generateTabs()} 不向其传递值,因此 Tab 组件的文章和主题将为空。

      return  <Tab tabType = 'tab' className ='nws-container-mid' topic = {topic} article = {article}  />
    

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 2022-11-17
      • 2020-12-24
      • 2020-08-21
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多