【问题标题】:Show only every 4th item from api data in ReactJs仅显示 ReactJs 中 api 数据中的每 4 个项目
【发布时间】:2021-06-06 05:46:00
【问题描述】:

从 API 我得到一个包含 40 个对象的数组。我只想显示 5 个项目。所以我的想法是只显示第 4 个项目,并跳过其他项目。我的想法是先过滤数组,如果满足条件,就会返回数据,可能使用map?

const Weather = () => {

  const [key, setKey] = useState([]);
  const [data, setData] = useState({
    city: "",
    country: ""
  })

  const API = '28876c50c36221de5f008fa752cb3f1a';

  const dataWeather = async () => {
    await axios.get(`https://api.openweathermap.org/data/2.5/forecast?q=${data.city},${data.city}&appid=${API}`)
      .then(res => {
        console.log(res.data)
        // const {resData} = res.list;
        const { list: resData } = res.data
        console.log(resData);
        setKey(resData);
      })
  }

  const handleClick = (e) => {
    const { name, value } = e.target;
    setData(prev => {
      return {
        ...prev,
        [name]: value
      }
    })
  }

  const trigger = (e) => {
    e.preventDefault();
    dataWeather()
  }
  return (
    <Form>
      <Container>
        <Form>
          <Form.Row>
            <Col>
              <Form.Control placeholder="City" onChange={handleClick} name="city" value={data.city} />
            </Col>
            <Col>
              <Form.Control placeholder="Country" onChange={handleClick} name="country" value={data.country} />
            </Col>
            <Button variant="primary" type="submit" onClick={trigger}>
              Submit
      </Button>
          </Form.Row>
        </Form>


        <div className="grid">
          {
            key !== null && (
              key.map(dataMap => 
              if (dataMap.dt_txt % 4 === 0) {
                <Card data={dataMap.weather[0].description} date={dataMap.dt_txt} imgSrc={dataMap.weather[0].icon} temp={Math.floor(dataMap.main.temp - 273.15)} />

              }
              )
            )

          }
        </div>

      </Container>
    </Form>
  )
}

【问题讨论】:

  • 我认为你应该分享工作代码,因为这看起来不起作用。
  • 对不起,我只发布特定的

标签: javascript arrays reactjs loops


【解决方案1】:

使用% 余数运算符保留每第 N 个项目,并跳过其他项目。

list.filter((item, index) => index % 4 === 0)

【讨论】:

  • 这是一个很好的过滤器示例,但为了使其成为一个完整的答案,请为 OP 解释它以及如何在其特定情况下实现它。
  • 他问如何从列表中跳过 5 项中的 4 项,这不是实现了吗?
  • 如果满足过滤条件思想,我还应该使用map返回组件吗?
  • filter 从列表中删除项目,但保留项目的结构。当您想要转换列表中项目的形式时,您必须使用map
【解决方案2】:

map() 将始终返回一个与调用它的长度相同的数组,因此如果不直接改变元素就无法删除元素,这不适合使用该方法。

话虽如此,React 将接受值为 falsenullundefinedtrue 的子级,但不会渲染它们。因此,您可以简单地为不想渲染的元素返回 null,而不是显式过滤。

key &&
key.map((dataMap, index) => {
  if (index % 4 === 0) {
    return <Card data={dataMap.weather[0].description} date={dataMap.dt_txt} imgSrc={dataMap.weather[0].icon} temp={Math.floor(dataMap.main.temp - 273.15)} />
  } else {
    return null;
  }
}

或者,您可以在映射之前应用过滤器调用。 filter() 返回一个元素数组,这些元素返回 true 用于传递的条件。然后,您可以在返回的数组上链接您的 map() 调用。

key &&
  key
    .filter((_, index) => index % 4 === 0)
    .map(dataMap => (
      <Card data={dataMap.weather[0].description} date={dataMap.dt_txt} imgSrc={dataMap.weather[0].icon} temp={Math.floor(dataMap.main.temp - 273.15)} />
    )

【讨论】:

    猜你喜欢
    • 2021-02-12
    • 2019-06-17
    • 2018-02-20
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多