如何在reactjs中将参数传递给函数?

问题描述 投票:0回答:2

如何将sport_id形式getSport发送到getEvents来展示每个体育赛事?

我可以将getSport函数放到其他组件中,在此组件中调用并使用它吗?

事件json:

[
  {
    "id": "912653",
    "time": "1536471082",
    "time_status": "1",
    "league": {
      "id": "900",
      "name": "Hong Kong 2nd Division",
      "cc": "hk"
    },
    "home": {
      "id": "13767",
      "name": "Yau Tsim Mong",
      "image_id": "193606",
      "cc": "hk"
    },
    "away": {
      "id": "63770",
      "name": "Tuen Mun SA",
      "image_id": "56045",
      "cc": "hk"
    },
    "timer": {
      "tm": 74,
      "ts": 25,
      "tt": "1",
      "ta": 0
    },
    "scores": {}
  }
]

体育json:

[
  {
    "id": 8,
    "name": "Rugby Union",
    "is_active": null,
    "slug": "rugby-union"
  }
]

这是我的代码:

import React, { Component } from "react";
import axios from "axios";
import moment from "moment";

export default class Feutred extends Component {
  state = {
    sports: [],
    events: [],
    isLoading: true,
    errors: null
  };
  getSports() {
    axios
      .get("/api/v1/sports.json")
      .then(response =>
        response.data.map(sport => ({
          id: sport.id,
          name: sport.name,
          slug: sport.slug
        }))
      )
      .then(sports => {
        this.setState({
          sports,
          isLoading: false
        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }
  getEvents() {
    axios
      .get("/api/v1/events?sport_id=${sport_id}")
      .then(response =>
        response.data.map(event => ({
          id: event.id,
          time: event.time,
          league: event.league,
          time_status: event.time_status,
          homeTeam: event.home,
          awayTeam: event.away
        }))
      )
      .then(events => {
        this.setState({
          events,
          isLoading: false
        });
      })
      .catch(error => this.setState({ error, isLoading: false }));
  }
  componentDidMount() {
      this.getSports();
      (this.interval = setInterval(
        () => this.getEvents({ time: Date.now() }),
        12000
      ));
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    const { sports, isLoading } = this.state;
    return (
      <React.Fragment>
        {!isLoading ? (
          sports.map(sport => {
            const { id, name } = sport;
            return (
              <div key={sport.id}>
                <div className="text">
                  <p className="meta">
                    <span className="matchinfo">
                      <span className="block">time</span>
                      <span className="block">timestatus</span>
                    </span>
                  </p>
                  <h3>
                    <a href="">home-team vs aya tream</a>
                  </h3>
                  <p className="league">
                    <a className="watchlive" href="">
                      <span className="icon" />
                      <span>Watch live</span>
                    </a>
                    <span>{sport.name} - league cc - league name</span>
                  </p>
                </div>
              </div>
            );
          })
        ) : (
          <p>Loading...</p>
        )}
      </React.Fragment>
    );
  }
}
reactjs
2个回答
0
投票

只是去构造它 - 在一个组件中加载运动然后渲染一些<EventsLoadingComponent />通过运动id作为道具...

提示:在'main return'之前在渲染中使用if(isLoading) return <p>Loading...</p> - 不需要在返回JSX中使用三元运算符。

更新:

render() {
  const { sports, isLoading } = this.state;
  if(isLoading) return <p>Loading...</p>
  return (
    <React.Fragment>
      {sports.map(sport => <EventsLoadingComponent sport={sport}/>}
    </React.Fragment>
  );
}

getEvents移动到<EventsLoadingComponent/> - 你将会因与this.props.sport.id有关的事件而出现并将它们渲染出来。这样,每个都可以单独更新。

记得在最顶层的html元素中使用key

更新#2:

你可以把你的代码与我的代码进行比较吗?

您的代码 - 线性,程序性,'平面模板驱动',强制异步同步,一体化组件......而html是树状结构的(展平视图)。

React thinking(通常,不仅仅是我的代码) - 更多OO,构建与数据和视图结构更密切相关的对象树,赋予它们自己的责任(数据处理,视图)。更易于阅读,扩展(将更多细节解构为组件 - 甚至是单行),适合装饰,易于管理和重复使用。

结构渲染中的对象通常只传递子(或没有)只提供功能。可用的复杂程度更高,在html中,此结构内的通信比(可以完成)更容易(并且更少依赖)。


0
投票

像这样的东西:

getEvents({ id }) {
    axios
      .get(`/api/v1/events?sport_id=${id}`)
      ...
  }

  componentDidMount() {
    this.getSports()
      .then(() => {
        return Promise
          .all(this.state.sports.map(this.getEvents))
      });
    ...
  }

注意:

您需要优化保存数据的方式,因为您需要知道哪些事件适用于哪项运动。

© www.soinside.com 2019 - 2024. All rights reserved.