我在更改 React 中的計數值時遇到了麻煩。
我有動態集,我想在它改變時渲染集的大小!
所以我想在ratedSet 的大小發生變化時將更新計數變數保持為ratedSet.size 。
我知道 useSet 不會再次渲染,直到事情結束,所以我嘗試使用 useEffect 并且它仍然無法作業。我想我沒有正確使用它。
每當它發生變化時,如何顯示集合的大小?
以下是我的代碼。我對我嘗試做的事情添加了一些評論:
import React, { useEffect, useState } from "react";
import BoardCardMain from "./component/BoardCardSurvey";
//other import statements
export default function Survey() {
const [gameList, setGameList] = useState<Game[]>([]);
const [count, setCount] = useState(0); //This is the count variable that I want to keep update
const [width] = useState(window.innerWidth);
let ratedSet = new Set(); //this is the set that I want to keep track of
let cnt = 0;
useEffect(() => {
setGameList(tempData.gameList);
}, []);
// I tried to do this but im not even close to answer...
useEffect(() => {
setCount(ratedSet.size);
}, [ratedSet.size]);
//This is the part I am changing the size of set dynamically
//I am getting gameNo and score from child tsx, and am updating the set based on it
const countHandler = (ratedGameNo: number, score: number) => {
if (score > 0) {
ratedSet.add(ratedGameNo);
} else {
ratedSet.forEach((item) => {
if (item === ratedGameNo) {
ratedSet.delete(item);
}
});
}
//So here, if I console.log(ratedSet.size), it gives me correct values.
//but if i do setCount(ratedSet.size) it only updates once and never change again
};
return (
<>
SIZE IS : {count}
SIZE IS : {ratedSet.size}
None of them works
<Box> I am updating my set with below map : </Box>
<Container style={{ marginTop: 20, padding: 10 }}>
<Grid container spacing={2}>
{gameList.map((game) => (
<BoardCardMain
key={game.gameNo}
game={game}
parentCallback={countHandler}
></BoardCardMain>
))}
</Grid>
</Container>
</>
);
}
const tempData = {
gameList: [
{
gameNo: 1,
gameImg:
"https:/",
},
{
gameNo: 12,
gameImg:
"https://",
},
{
gameNo: 2,
gameImg:
"https://r",
},
],
};
uj5u.com熱心網友回復:
因為ratedSet不是組件的狀態。改變集合不會導致組件重新渲染。所以useEffect(() => {}, [ratedSet.size])鉤子不會再次執行。
我認為有兩種解決方案:
- 當對
ratedSet.
const forceUpdate: () => void = React.useState()[1].bind(null, {});
- 保持
ratedSet狀態,您可以創建一個自定義鉤子,如useSet。(推薦)
而你宣告的ratedSet內部函陣列件可能是錯誤的。因為每次渲染組件時,都會創建一個新的。
uj5u.com熱心網友回復:
我嘗試使用 Effect 和 forceUpdate 但這兩個都不起作用。而且我嘗試使用 useSet 并且以某種方式我希望能夠在安裝軟體包時匯入它。
我沒有使用 useSet,而是按照建議將 rateSet 設定為狀態,現在可以使用:D
我洗掉了 Set 并改為使用陣列*
const [count, setCount] = useState(0);
const [ratedGame, setRatedGame] = useState<number[]>([]);
const countHandler = (ratedGameNo: number, score: number) => {
if (score > 0) {
if (ratedGame.length === 0) {
ratedGame.push(ratedGameNo);
setCount(count 1);
} else {
let found = ratedGame.includes(ratedGameNo) ? true : false;
if (found) {
} //do nothing
else {
setCount(count 1);
ratedGame.push(ratedGameNo);
}
}
} else if (score === 0) {
setCount(count - 1);
var index = ratedGame.indexOf(ratedGameNo);
if (index !== -1) {
ratedGame.splice(index, 1);
}
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/453274.html
下一篇:在選項卡導航器中添加堆疊導航器
