如何动态更改变量的值、更改状态和更新 UI

时间:2021-05-11 15:03:43

标签: javascript reactjs api react-hooks

我需要在满足特定条件后更改变量的值。似乎是一个简单的问题,但由于我是 React 的新手,也许有人可以帮助我。我尝试了几个选项 useEffect, useRef 一个带有简单 if/else 语句三元运算符的函数,但没有成功。在下面的代码中,我需要更改 let currentMatchDay = matchDay - 1 的值;让 currentMatchDay = matchDay;满足条件后,仅此而已。 let schedule = program.every(match => match.status === "FINISHED");是有条件的。 所有数据都从两个 RESTAPI 的端点获取,并从上下文和排名组件导入。 谢谢!

import React, { useEffect, useCallback } from "react";
import styles from "./styles/Recent.module.css";
import { useGlobalContext } from "./Context";
import { useGlobalState } from "./Standings";

const Recent = () => {

  const [lastGames, setLastGames] = React.useState([]);
  const [program, setProgram] = React.useState([]);

  const { state } = useGlobalContext();
  const { matchDay } = useGlobalState();

  //let scheduled = program.every(match => match.status === "FINISHED");

  let currentMatchDay = matchDay - 1   
  let upcomingGame = currentMatchDay + 1;
  let recent = state.slice(currentMatchDay - 1, currentMatchDay);
  let upcoming = state.slice(upcomingGame - 1, upcomingGame);

  const getLastGames = useCallback(() => {
    for (let games of recent) {
      setLastGames(games);
    }
  }, [recent]);

  const getProgram = useCallback(() => {
    for (let games of upcoming) {
      setProgram(games);
    }
  }, [upcoming]);

  useEffect(() => {
    getLastGames();
    getProgram();
  }, [getLastGames, getProgram]);


  return (
    <>
  <div className={styles.container}>
    <div className={styles.matches}>
      <div className={styles.gamesnRound}>
        <div className={styles.alleWedstrijden}>Recent gespeeld</div>
        <div className={styles.speelrondes}>
          Speelronde
          <div className={styles.circle}>
            <div className={styles.dayNumber}>{currentMatchDay}</div>
          </div>
        </div>
      </div>

      {lastGames.map((game) => {
        const { homeTeam, awayTeam, score, id } = game;

        return (
          <div className={styles.match} key={id}>
            <div className={styles.teams}>
              <div className={styles.hometeam}>{homeTeam.name}</div>
              <div className={styles.scores}>
                {score.fullTime.homeTeam} : {score.fullTime.awayTeam}
              </div>
              <div className={styles.awayteam}>{awayTeam.name}</div>
            </div>
          </div>
        );
      })}
    </div>
  </div>
  </>
   )

1 个答案:

答案 0 :(得分:0)

如果您尝试显示 currentMatchDay,可以使用三元运算符来执行此操作。

<div className={styles.circle}>
            <div className={styles.dayNumber}>{program.every(match => match.status === "FINISHED")?matchDay:matchDay-1}</div>
 </div>

或者 use 可以定义一个可以返回 currentMatchDay 值的函数

const getCurrentDay=()=>{
if(program.every(match => match.status === "FINISHED"){
return matchDay}
return matchDay-1
}

 <div className={styles.circle}>
                <div className={styles.dayNumber}>{getCurrentDay()}</div>
     </div>