【问题标题】:prop value is undefined on first but not on second renderprop 值在第一次渲染时未定义,但在第二次渲染时未定义
【发布时间】:2023-01-14 21:44:27
【问题描述】:

我在 react 18.2.0 nextjs1 0.1.0 节点 v18.12.1 上运行。

我遇到了一个奇怪的情况,在第一个渲染中,一个道具是未定义的,但在第二个渲染中它有它。该变量在父级的开头定义:

default function Home() {
    console.log('executing home');
.
.
    let LocationsData = [];
    console.log('defined LocationsData',LocationsData.length); 
.
.
.
    return (
        <> 
            <BuildCountrieslist data={LocationsData} />
        </>
)}

function BuildCountrieslist(props){
    console.log('started BuildCountrieslist , Data.length is', props.data.length); 
}

console.log 显示:

executing home     (as expected)
defined LocationsData 0 (as expected)  
started BuildCountrieslist , **Data.length is undefined ( the error in question)**
executing home     (as expected)
defined LocationsData 0 (as expected)
BuildCountrieslist , Data.length is 0 (as expected)

【问题讨论】:

  • 如果您不复制加载 LocationsData 的代码,我们如何提供帮助?
  • 你好 Hugo,恐怕我不明白你为什么要求将数据加载到 LocationsData 的代码。它首先初始化为一个空数组,它的初始长度(在第一次渲染时)应该是 0,并且控制台日志的消息不应该说“未定义”

标签: reactjs


【解决方案1】:

function App() {
  console.log('executing home');
  let LocationsData = [];
  console.log('defined LocationsData', LocationsData.length);
  return (
    <>
      <BuildCountrieslist data={LocationsData} />
    </>
  )
}

function BuildCountrieslist(props) {
  console.log('started BuildCountrieslist , Data.length is', props.data.length);
}

export default App

应该是这样的

【讨论】:

  • 我可以确认最小可重现示例不会重现错误,因此它不是反应中的错误 :-) 我不知道在 js 中,可以将变量设置为未定义和/或显式删除。我的代码没有将 LocationsData 设置为未定义或将其删除。任何人都可以提出这种行为的任何其他可能原因吗?
【解决方案2】:

是我的错,(手放在脸上) 事实上,我有一些代码,之后 LocationsData 被设置为未定义。 对不起 :-(

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-22
    • 2021-11-10
    • 2016-07-11
    • 2020-07-17
    • 1970-01-01
    • 2022-10-08
    • 2021-10-31
    • 2022-09-23
    相关资源
    最近更新 更多