我有这个反应码:
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不能工作?我的代码中有遗漏什么吗?
发布于 2022-10-15 20:51:05
状态(和道具)的一个好的经验法则是,当一个值可以完全由另一个值确定时,避免重复状态值。否则,您可能会遇到这样的问题,在这些问题中,保持多个状态保持同步可能比需要的更具有挑战性。
在这里,您可以在组件挂载时设置playerCount的初始值:
const [playerCount, setPlayerCount] = useState(players.length);组件只挂载一次--此时,players是空数组--因此playerCount变为0,因为您从不调用setPlayerCount,所以它始终保持为0。
虽然您可以通过在您的setPlayerCount中调用.then来修复它,但更好的方法是只在需要时从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>
);
}https://stackoverflow.com/questions/74082905
复制相似问题