矩形钩道具与状态交流问题

时间:2019-03-23 13:32:20

标签: javascript reactjs react-hooks

我正在尝试基于React Hooks构建我的第一个React App,并且很难弄清状态/道具和渲染的状态。我正在创建一些小型猜谜游戏。

我有一个上级组件GameContent,该组件将一些道具传递给其子对象(圆形):

  • currentRound(数字)
  • roundData(对象)
  • shiftRounds(函数)

通过“ shiftRounds”,我告诉我的父级组件:“此玩家给出了正确答案”,然后函数进行了四舍五入并得分(均为父母状态)。

虽然看起来很容易,但是我在子组件中的函数会检查答案是否正确,总是从第一轮获取数据。

我尝试了React.useRef,尝试了不同的状态配置,但仍然找不到解决方案。

<GameContent />

const GameContent = ({ gameOptions, gameFinish }) => {

  const [gameData, setGameData] = useState([]);
  const [round, setRound] = useState(1);
  const [score, setScore] = useState([0, 0]);

  const [ligue, dateFrom, dateTo, rounds, player1, player2] = gameOptions;

  useEffect(() => {
    //
    // Function fetches football matches. 
    //
    (async () => {
      const matchesData = await fetchMatches(ligue, dateFrom, dateTo)
      setGameData(matchesData);
    })();
  }, [])

  const nextRound = (scoringPlayer) => {
    if (round <= rounds) {
      setScore(score => {
        score[scoringPlayer] += 1;
        return score
      });
      setRound(round => round + 1);
    } else {
      finishGame()
    }
  }

  return (
    <div className="text-center">
      <h2>Round {round}</h2>
      <h3>Score</h3>
      <h2>{`${score[0]} : ${score[1]}`}</h2>
      {(gameData.length) ? <Round currentRound={round} roundData={gameData[round - 1]} shiftRounds={nextRound} players={[player1, player2]} /> : <h1>Loading...</h1>}
    </div>
  )
}

<Round />

const Round = (props) => {
  const [isCheckingAnswer, setIsCheckingAnswer] = useState(false);

  useEffect(() => {
    //
    // Set eventListeners for keydown (too capture player's answer)
    //
    document.addEventListener('keydown', (e) => { handleKeyPress(e) });
    setIsCheckingAnswer(false);
    return () => {
      document.removeEventListener('keydown', (e) => { handleKeyPress(e) });
    }
  }, [props.roundData])

  const handleKeyPress = (e) => {
    if (!isCheckingAnswer) {
      e.preventDefault();
      setIsCheckingAnswer(true);
      if (keysMap[e.key] === checkGoodAnswer(props.roundData.homeTeamScore, props.roundData.awayTeamScore)) {
        const winingPlayer = isNaN(e.key / 2) ? 0 : 1;
        props.shiftRounds(winingPlayer);
      } else {
        setIsCheckingAnswer(false);
      }
    } else {
      return
    }
  }
  return (
    <>
      <Row>
        <Col xs={4}>
          <h2>{props.roundData.homeTeam}</h2>
        </Col>
        <Col xs={4}>
          <h2>vs</h2>
        </Col>
        <Col xs={4}>
          <h2>{props.roundData.awayTeam}</h2>
        </Col>
      </Row>
      <Row className="justify-content-center my-5">
        <Col xs={4}>
          <h3>{props.players[0]}</h3>
        </Col>
        <Col xs={4}>
          <h3>{props.players[1]}</h3>
        </Col>
      </Row>
    </>
  )
}

助手功能

const checkGoodAnswer = (homeTeamScore, awayTeamScore) => {
  if (homeTeamScore > awayTeamScore) {
    return 'homeTeam'
  } else if (homeTeamScore < awayTeamScore) {
    return 'awayTeam'
  } else {
    return 'draw'
  }
}

const keysMap = {
  'a': 'homeTeam',
  'w': 'draw',
  'd': 'awayTeam',
  '4': 'homeTeam',
  '8': 'draw',
  '6': 'awayTeam',
}

获取的数据样本:

[
{awayTeam: "Paris Saint-Germain FC"
awayTeamScore: 2
homeTeam: "Manchester United FC"
homeTeamScore: 0},
{
awayTeam: "FC Porto"
awayTeamScore: 1
homeTeam: "AS Roma"
homeTeamScore: 2
},
...
]

2 个答案:

答案 0 :(得分:1)

您应该添加 ALL 个相关变量/函数,这些变量/函数在您的useEffect中用作依赖项。

docs

  

...确保数组包含组件范围内随时间变化并被效果使用的所有值(例如props和state)

例如,在您的第一个效果中,数组中没有依赖项:

useEffect(() => {
    //
    // Function fetches football matches. 
    //
    (async () => {
      const matchesData = await fetchMatches(ligue, dateFrom, dateTo)
      setGameData(matchesData);
    })();
  }, [])

但是您确实使用liguedateFromdateTo等...

react团队提供了一个不错的eslint插件(eslint-plugin-react-hooks),可帮助您解决此类问题,我建议您尝试一下。

答案 1 :(得分:0)

我找到了解决方案。问题在于addEventListener中调用的函数范围, 我这样称呼它:

document.addEventListener('keydown', (e) => { handleKeyPress(e) });

但正确的调用方式是:

document.addEventListener('keydown', handleKeyPress);

萨吉夫还指出,在useEffect中,所有随时间变化并在内部使用的变量都应包含在数组中,如下所示:

 useEffect(() => {
      document.addEventListener('keydown', (e) => { handleKeyPress(e) });
      setIsCheckingAnswer(false);
      return () => {
        document.removeEventListener('keydown', (e) => { handleKeyPress(e) });
      }
    }, [props.roundData])