渲染运行两次

时间:2020-04-20 15:10:41

标签: javascript reactjs gatsby

我有一个国家清单,我想显示一些与该国家有关的信息。我运行一个循环以显示每个国家的信息。我已经为一个国家创建了一个组件。

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

0 个答案:

没有答案
相关问题