为什么简单的useState初始化不起作用?

y3bcpkx1  于 2022-10-21  发布在  iOS
关注(0)|答案(1)|浏览(214)

我有这个React代码:

import React, { useState, useEffect } from "react";
import axios from "axios";

function App() {
  const [players, setPlayers] = useState([]);

  // Get all Players
  const getAllPlayersUrl = "http://localhost:5087/api/GetAllPlayers";
  useEffect(() => {
    axios.get(getAllPlayersUrl).then((response) => {
      setPlayers(response.data);
    });
  }, []);

  const [playerCount, setPlayerCount] = useState(players.length);

  return (
    <div>
      <p>{`This is how many there are: ${playerCount}`}</p>
    </div>
  );
}

export default App;

我想打印使用playerCount变量的初始玩家数量。然而,它说它是零:
数量是这样的:0
如果我打印players.length,它将输出正确的数字:

<p>{`This is how many there are: ${players.length}`}</p>

数量如下:9个
即使我移除依赖数组以保持呈现,playerCount仍然不会更新:

useEffect(() => {
    axios.get(getAllPlayersUrl).then((response) => {
      setPlayers(response.data);
    });
  });

我想知道为什么useState不起作用?我的代码中有什么遗漏的地方吗?

e4yzc0pl

e4yzc0pl1#

对于状态(和道具),一个很好的经验法则是,当一个值可以完全由另一个值确定时,避免复制状态值。否则,您可能会遇到这样的问题,在这些问题中,保持多个状态同步可能比需要的更具挑战性。
这里,您可以在组件挂载时设置playerCount的初始值:

const [playerCount, setPlayerCount] = useState(players.length);

并且该组件只挂载一次--此时,players是空数组--因此playerCount变为0,并且因为您从不调用setPlayerCount,所以它始终保持为0。
虽然您可以通过在.then中调用setPlayerCount来修复它,但更好的方法是仅在需要时才从players状态计算玩家数量:

function App() {
  const [players, setPlayers] = useState([]);
  const getAllPlayersUrl = "http://localhost:5087/api/GetAllPlayers";
  useEffect(() => {
    axios.get(getAllPlayersUrl).then((response) => {
      setPlayers(response.data);
    });
  }, []);

  return (
    <div>
      <p>{`This is how many there are: ${players.length}`}</p>
    </div>
  );
}

或者,如果真的必须这样做,则根据players数组来记录计数(而不创建额外的状态)。

function App() {
  const [players, setPlayers] = useState([]);
  const playerCount = useMemo(() => players.length, [players]);
  const getAllPlayersUrl = "http://localhost:5087/api/GetAllPlayers";
  useEffect(() => {
    axios.get(getAllPlayersUrl).then((response) => {
      setPlayers(response.data);
    });
  }, []);

  return (
    <div>
      <p>{`This is how many there are: ${playerCount}`}</p>
    </div>
  );
}

相关问题