简体   繁体   English

如何让子组件使用 App.js 道具数据中的 map()?

[英]How to make child components use map() from App.js props data?

My react is 18.2.我的反应是18.2。 I want the child component to receive data and use map() from App.js.我希望子组件从 App.js 接收数据并使用 map()。

I checked the child component received the data, but I don't know why does it can't use map().我检查了子组件收到数据,但不知道为什么它不能使用map()。

It shows this error.它显示了这个错误。

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

So do anyone can fix it?那么有人可以修复它吗? I guess this is render problem, but I don't know how to fix it, thank you.我想这是渲染问题,但我不知道如何解决它,谢谢。

fetched():获取():

[
  { id:1, date: '2011-01-01T00:00:00.000Z' },
  { id:2, date: '2013-09-03T00:00:00.000Z' },
  { id:3, date: '2012-04-02T00:00:00.000Z' },
  { id:4, date: '2013-12-08T00:00:00.000Z' },
  { id:5, date: '2010-01-23T00:00:00.000Z' },
];

App.js:应用程序.js:

import { Child } from './Child';

const Test = () => {
  const [toChild, setToChild] = useState()
  useEffect(() => {
    const data = async () => {
      const fetchedData = await fetched();
      setToChild(fetchedData)
    };
    data();
  }, []);

  const test = () => {
    setToChild(fetchedData)
  }
}

return(<Child toChild={toChild}>)

Child.js: Child.js:

const Child = ({ toChild }) => {
  const data = toChild;

  const getDate = data.map((item) => item.date);

Since the data coming from your fetch is an array of objects, you may want to initialize the state as an empty array useState([]) , useEffect will fire once the component has been mounted so at first, toChild will be undefined and that's why you are getting that error.由于来自您的 fetch 的数据是一个对象数组,您可能希望将 state 初始化为一个空数组useState([]) ,一旦安装了组件, useEffect就会触发,所以首先, toChild将是undefined的,这就是为什么你得到那个错误。 So basically:所以基本上:

import { useState, useEffect } from 'react'
import { Child } from './Child';

const Test = ()=>{
const [toChild,setToChild] = useState([])

useEffect(() => {
    const data = async () => {
      const fetchedData = await fetched();
      setToChild(fetchedData)
    };
    data();
  }, []);

return <Child toChild={toChild} />

Jsx is already rendered before javascript in react even though you fetch the data from server but html already rendered to the browser.so add any loading component to that. Jsx 已经在 javascript 之前渲染,即使您从服务器获取数据但 html 已经渲染到浏览器。所以添加任何加载组件。 toChild?:<div>loading</div>:<Child toChild={toChild}/>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM