首页 > 解决方案 > 渲染运行两次

问题描述

我有一个国家列表,我想显示一些与该国家相关的信息。我运行一个循环以显示每个国家/地区的信息。我为一个国家/地区创建了一个组件。

const CountryCard = ({ info }) => {
  const { country, infoForLastDate, path } = info
  return (
    <Card >
      <CardContent>
        <Typography variant="h5" component="h2" >
          {country.name}
        </Typography>
        <Flag oneToOne={country.oneToOne} fourToThree={country.fourToThree} />
        <Typography variant="body2" >
          Confirmed: {infoForLastDate.confirmed}
        </Typography>
        <Typography variant="body2" component="p">
          Recovered: {infoForLastDate.recovered}
        </Typography>
        <Typography variant="body2" component="p">
        Deaths: {infoForLastDate.deaths}
        </Typography>
      </CardContent>
      <CardActions>
        <Link href={path}>
          See more
        </Link>
      </CardActions>
    </Card>
  )
}

export default CountryCard

此外,我还创建了另一个组件来显示与国家相关的国旗。

import React from 'react'
import { imageUrlFor } from '../lib/image-url'

const Flag = ({ oneToOne, fourToThree }) => {
  const  url = imageUrlFor(oneToOne.asset._id)

  return (
    <img src={url} />
  )
}

export default Flag

我得到错误TypeError: oneToOne is null

我不知道为什么旗帜渲染两次。当我调试时,第一次 oneToOne属性有一个值,但最后再次运行并且是null

为什么会这样?

编辑:添加 CountryList 组件:


const CountryList = ({list}) => {
  return (
    <Grid container spacing={3}>
      { list.length > 1 && list.map(country => {
        const countryWithPath = {
          ...country,
          path: `/country/${country.country.name.toLowerCase().replace(' ', '-').replace('*', '')}`
        }
        return (
          <Grid item xs={12} sm={6} key={country._id} >
            <CountryCard info={countryWithPath} />
          </Grid>)
      })
      }
    </Grid>
  )
}

export default CountryList

标签: javascriptreactjsgatsby

解决方案


推荐阅读