简体   繁体   English

React - 使用从父组件传递的道具渲染子组件时出错

[英]React - Error while rendering child component with prop passed from parent component

I have a problem while creating my react app.创建我的反应应用程序时遇到问题。 I'm fetching data from CoinGecko API to build a crypto tracking app, but when I pass the data prop from the parent App.js to the child Info.js .我正在从 CoinGecko API 获取数据以构建加密跟踪应用程序,但是当我将data道具从父App.js传递给子Info.js When I try to render the page it gives me Info.js:45 Uncaught TypeError: Cannot read properties of undefined (reading 'large') .当我尝试渲染页面时,它给了我Info.js:45 Uncaught TypeError: Cannot read properties of undefined (reading 'large') I really don't understand why it happens.我真的不明白为什么会这样。

App.js应用程序.js

function App() {
  const [isToggled, setIsToggled] = useState(false);
  const [data, setData] = useState({});
  const [coin, setCoin] = useState("bitcoin");

  const getData = () => {
    axios({
      method: "GET",
      url: `https://api.coingecko.com/api/v3/coins/${coin}?localization=en`,
    })
      .then((response) => {
        console.log(response.data);
        setData(response.data);
        
      })
      .catch((err) => {
        console.log(err);
      });
  };

  useEffect(() => {
    getData(coin);
  }, []);

  return (
    <div>
      <HeaderContainer />
      <Search getData={getData} coin={coin} setCoin={setCoin} />
      <Info mcap={mcap} data={data} />
    </div>
  );
}

Info.js Info.js

function Info({ image, mcap, data }) {
 return (
    <div className="info-container">
      <div className="left-column">
        <div className="top-row">
          <div className="coin-icon-container">
            <img
              className="coin-icon"
              src={data.image.large}
              alt="coin logo"
              width="40px"
              height="40px"
            ></img>
          </div>
          <div className="coin-name-container">
            <p className="coin-name">{data.name}</p>
            <p className="coin-abbr">{data.symbol}</p>
          </div>
          <div className="coin-MCAP-details">
            <p className="coin-position">#{data.market_cap_rank}</p>
            <p className="coin-MCAP">{data.market_data.market_cap.usd}</p>
          </div>

The same error happens with the market cap in the second to last line of code.在倒数第二行代码中的市值也会出现同样的错误。 data.name and data.symbol render correctly. data.namedata.symbol正确呈现。

The response.json file is very long, so i'll just put the important parts: response.json文件很长,所以我只放重要部分:

Response.json响应.json

{
    "id": "bitcoin",
    "symbol": "btc",
    "name": "Bitcoin",
    "asset_platform_id": null,
     .......
    "image":{
    "thumb": "https://assets.coingecko.com/coins/images/1/thumb/bitcoin.png?1547033579",
    "small": "https://assets.coingecko.com/coins/images/1/small/bitcoin.png?1547033579",
    "large": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579"
    }
    .........
}

SetData is by default an empty object, and because Axios request is called in useEffect . SetData默认是一个空的 object,因为 Axios 请求在useEffect中被调用。 On the first render Info component receives empty data object.在第一个渲染Info组件接收空data object。

To way to solve it.想办法解决。

  • Add Loading state.添加加载 state。
  • Or Add Optional chaining (data?.image?.large)或添加可选链接(data?.image?.large)

暂无
暂无

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

相关问题 将 prop 从父组件传递给子组件时出错 - Error with passing a prop from parent to child component 从父组件传递道具在子组件 React 中变为空 - Passing a prop from a Parent component becomes null in the Child component React React-Slick轮播-在父级组件的prop触发下,自动播放在子级组件中不起作用 - React-slick carousel - autoplay not working in child component while triggering it with prop from parent component React中从父组件传递给子组件的“未定义”? - 'Undefined' passed from parent to child component in React? 传递了字符串属性以响应父级的子级组件-无法使用JSON.parse()转换为Object - String prop passed to react child component from parent - unable to conver to Object with JSON.parse() 反应状态作为道具传递给子组件未显示 - React state passed as prop to child component not showing 从父组件获取子组件 Prop - Getting Child Component Prop from the Parent Component React 子组件不会更新从父组件传递的属性 - React Child Component does not update properties passed from Parent Component 使用 React Hooks,当我将 prop 从父组件传递给子组件时,子组件中的 prop 未定义 - Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined 无法加载通过 React App 中的父组件作为道具传递给子组件的图像 - Can't load images passed on to a child component as a prop by parent component in a React App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM