How can I fix 'Cannot read properties of undefined' error when accessing prop values in a child component in React?

huangapple go评论58阅读模式
英文:

How can I fix 'Cannot read properties of undefined' error when accessing prop values in a child component in React?

问题

I'm trying to access the value of an array fileList that I pass as a prop to a component <FileDisplay prop={filesList}/>, but when I try to read a property of the array {JSON.stringify(props.prop[0].name)} I get an error:

Cannot read properties of undefined (reading 'name')
TypeError: Cannot read properties of undefined (reading 'name')

but I can read JSON.stringify(props.prop[0]) without getting any errors.

Also, if I first run the code with {JSON.stringify(props.prop[0].name)} commented out and then uncomment it and save the code, react compiles again and I am able to read the value of props.prop[0].name.

From my understanding, the code is trying to read the props.prop[0].name before the promise returns and filesList value is set. Is there a way to fix this?

export default function Home() {

    const { user, setUser } = useContext(UserContext);
    const [ filesList, setFilesList ] = useState([])

    useEffect(() => {
      const getData = async () => {
        const listFiles = await listAll(ref(storage, 'files'))
        const data = await  Promise.all(listFiles.items.map(async (itemRef) => {
          const response = getMetadata(ref(storage, 'files/' + itemRef.name))
          return response
        }))
        setFilesList(data)
      }
      getData()
    }, [])

 return (
    <div>
      
      <div>
        <FileDisplay prop={filesList}/>
      </div>
      
    </div>
    
  )
}
export default function FileDisplay(props) {    
  return (
    <div>
       <h2>LIST OF FILES</h2>
        <p>{JSON.stringify(props.prop)}</p>
        <p>-----------------------</p>
        <p>{JSON.stringify(props.prop[0])}</p>
        <p>-----------------------</p>
        <p>{JSON.stringify(props.prop[0]?.name)}</p>
    </div>
  )
}

I've tried to read the variable but I still can't access the properties.

英文:

I'm trying to access the value of a array fileList that I pass as a prop to a component &lt;FileDisplay prop={filesList}/&gt;, but when I try to read a property of the array {JSON.stringify(props.prop[0].name)} I get an error:

> Cannot read properties of undefined (reading 'name')
TypeError: Cannot read properties of undefined (reading 'name')

but I can read JSON.stringify(props.prop[0]) without getting any errors.

Also, if I first run the code with {JSON.stringify(props.prop[0].name)} commented out and then uncomment it and save the code, react compiles again and I am able to read the value of props.prop[0].name.

From my understanding, the code is trying to read the props.prop[0].name before the promise returns and filesList value is set. Is there a way to fix this?

export default function Home() {

    const { user, setUser } = useContext(UserContext);
    const [ filesList, setFilesList ] = useState([])

    useEffect(() =&gt; {
      const getData = async () =&gt; {
        const listFiles = await listAll(ref(storage, &#39;files&#39;))
        const data = await  Promise.all(listFiles.items.map(async (itemRef) =&gt; {
          const response = getMetadata(ref(storage, &#39;files/&#39;+ itemRef.name))
          return response
        }))
        setFilesList(data)
      }
      getData()
    }, [])

 return (
    &lt;div&gt;
      
      &lt;div&gt;
        &lt;FileDisplay prop={filesList}/&gt;
      &lt;/div&gt;
      
    &lt;/div&gt;
    
  )
export default function FileDisplay(props) {    
  return (
    &lt;div&gt;
       &lt;h2&gt;LIST OF FILES&lt;/h2&gt;
        &lt;p&gt;{JSON.stringify(props.prop)}&lt;/p&gt;
        &lt;p&gt;-----------------------&lt;/p&gt;
        &lt;p&gt;{JSON.stringify(props.prop[0])}&lt;/p&gt;
        &lt;p&gt;-----------------------&lt;/p&gt;
        &lt;p&gt;{JSON.stringify(props.prop[0].name)}&lt;/p&gt;
    &lt;/div&gt;
  )
}

I've tried to read the variable but I still can't access the properties

答案1

得分: 0

Your issue may be related to timing, specifically, the FileDisplay component is being created before the filesList state has been populated.

getData方法是异步的,所以您的组件在等待响应时会继续加载。这意味着FileDisplay组件很可能最初使用一个等于[](fileList的默认值)的props值创建,这将导致props.prop[0]返回undefined。

我建议有条件地加载FileDisplay组件:

<FileDisplay prop={filesList}/>

替换为

{filesList.length && <FileDisplay prop={filesList}/>}

这假定fileList始终至少有一个元素。如果不是这种情况,那么您应该用另一个指示文件获取已完成的状态变量替换filesList.length检查,例如:

const [isFetching, setIsFetching] = useState<boolean>(true)

然后在getData之内,在setFilesList(data)之前设置setIsFetching(false)

您还需要修改FileDisplay组件以处理props参数中的空数组。

英文:

Your issue may be related to timing, specifically, the FileDisplay component is being created before the filesList state has been populated.

The getData method is async so your component will continue to load while it waits for a response. This means the FileDisplay component is likely to be initially created with a props value equal to [] (fileList default value) which will result in props.prop[0] returning undefined.

I would suggest loading the FileDisplay component conditionally:

Replace

&lt;FileDisplay prop={filesList}/&gt;

with

{filesList.length &amp;&amp; &lt;FileDisplay prop={filesList}/&gt;}

This assumes that fileList will always have at least one element. If this is not the case then you should replace the filesList.length check with another state variable that indicates the fetch of files has completed. e.g.

const [ isFetching, setIsFetching ] = useState&lt;boolean&gt;(true)

then within getData set setIsFetching(false) just before setFilesList(data)

You would also need to modify the FileDisplay component to handle an empty array in props parameter.

huangapple
  • 本文由 发表于 2023年5月29日 21:12:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定