在React中使用AJAX更改div内容中的API数据

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

我用 React 创建了一个模板来显示这样的实时足球比分:

const LiveScore = () => {
const {direction} = useThemeProvider();
const [selectedDay, setSelectedDay] = useState(parseInt(dayjs().format('DD')));

return (
    <Spring className="card d-flex flex-column">
        <div className="card_header d-flex flex-column g-10" style={{paddingBottom: 20}}>
            <div className="d-flex justify-content-between align-items-center">
                <h3>{dayjs().format('MMMM')} matches</h3>
            </div>
            <Navigator active={selectedDay} setActive={setSelectedDay}/>
        </div>
        <div className="card_header d-flex flex-column g-10">
        <LeagueHeader img={english_premier} title="English Premier League" subtitle="Regular Championship" />
        </div>
        <div className={styles.grid}>
            <div className={styles.scroll}>
                <ScrollContainer height={0}>
                    <div className={`${styles.scroll_track} ${styles[direction]} track d-flex flex-column g-20`}>
                        {
                            matches.map((match, index) => (
                                <MatchMonthCard match={match} index={index} key={index}/>
                            ))
                        }
                    </div>
                </ScrollContainer>
            </div>
            <div className={`${styles.card} ${styles[direction]}`}>
                <MatchMonthCard match={matches[2]} variant="extended"/>
            </div>
        </div>
    </Spring>
  )
  }

the template here

类似此页面:点击我!

更改日期时我陷入自动更改比赛结果(从 API 获取数据)的困境?有什么想法吗?

编辑

我添加了按日期切换的按钮代码:

const Navigator = ({active, setActive}) => {
const {theme, direction} = useThemeProvider();
const [swiper, setSwiper] = useState(null);

useEffect(() => {
    if (swiper) {
        swiper.slideToLoop(parseInt(active) - 1);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [swiper, active]);

useEffect(() => {
    if (swiper) {
        swiper.changeLanguageDirection(direction);
        swiper.update();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [swiper, direction]);

return (
    <div className={`${styles.navigator} ${theme === 'light' ? styles.light : styles.dark}`}>
        <Swiper
            className="h-100"
            slidesPerView="auto"
            spaceBetween={10}
            centeredSlides={true}
            onSwiper={setSwiper}
            loop
            initialSlide={+active - 1}
        >
            {
                getMonthDays().map((day, index) => (
                    <SwiperSlide className={styles.slide} key={index}>
                        <div className={classNames(`${styles.navigator_item} ${styles[direction]}`, {[styles.active]: active === parseInt(day.date)})}
                             onClick={() => setActive(parseInt(day.date))}>
                            <h4 className={styles.day}>111111</h4>
                            <span className="label h6">{day.weekday}</span>
                        </div>
                    </SwiperSlide>
                ))
            }
        </Swiper>
    </div>
)

}

** 新编辑** 当前一天的新 JSON 文件:

{
"get": "fixtures",
"parameters": {
    "season": "2023",
    "date": "2024-01-15"
},
"errors": [],
"results": 67,
"paging": {
    "current": 1,
    "total": 1
},
"response": [
    {
        "fixture": {
            "id": 1150218,
            "referee": "Ismael Rosario Lopez Penuelas, Mexico",
            "timezone": "UTC",
            "date": "2024-01-15T00:00:00+00:00",
            "timestamp": 1705276800,
            "periods": {
                "first": 1705276800,
                "second": 1705280400
            },
            "venue": {
                "id": 1080,
                "name": "Estadio Victoria",
                "city": "Aguascalientes"
            },
            "status": {
                "long": "Match Finished",
                "short": "FT",
                "elapsed": 90
            }
        },
        "league": {
            "id": 262,
            "name": "Liga MX",
            "country": "Mexico",
            "logo": "https://media.api-sports.io/football/leagues/262.png",
            "flag": "https://media.api-sports.io/flags/mx.svg",
            "season": 2023,
            "round": "Clausura - 1"
        },
        "teams": {
            "home": {
                "id": 2288,
                "name": "Necaxa",
                "logo": "https://media.api-sports.io/football/teams/2288.png",
                "winner": true
            },
            "away": {
                "id": 2283,
                "name": "Atlas",
                "logo": "https://media.api-sports.io/football/teams/2283.png",
                "winner": false
            }
        },
        "goals": {
            "home": 2,
            "away": 1
        },
        "score": {
            "halftime": {
                "home": 0,
                "away": 1
            },
            "fulltime": {
                "home": 2,
                "away": 1
            },
            "extratime": {
                "home": null,
                "away": null
            },
            "penalty": {
                "home": null,
                "away": null
            }
        }
    },
    {
.....
....

我得到了当天的数据:

const [matches, setMatches] = useState([]);



const url = "http://127.0.0.1:8000/${date}";
const [data, setData] = useState([{}]);

const matchData = async () => {
  const res = await fetch(url);
    const d = await res.json();
    return setData(d.response);
}

useEffect(() => {
    matchData();
}, [{}]);
javascript reactjs ajax
1个回答
0
投票

关注我们在评论中的对话:

要在值更改时执行操作,您必须使用 useEffect 挂钩。该钩子有 2 个参数:第一个是回调(值更改时执行的操作),第二个是要监视的依赖项列表。

在您的情况下,依赖项是 selectedDay ,回调是对 matchData 的调用。但是,应修改 matchData 以使用与所选日期相对应的正确 URL。

这里是一个简单的重现。

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