[英]React Hook state updating without calling setState
I am running into an issue with React where my hook state is updating without my calling setState.我遇到了一个 React 问题,我的挂钩 state 在没有调用 setState 的情况下进行了更新。
const [dataSet2, setDataSet2] = React.useState([
[2, 3, 4],
[5, 6, 7],
[8, 9, 9],
]);
const badFunction = () => {
let selections = [];
let newSelections = [];
let winPercent = 0;
let newWinPercent = 1;
const depth = 2;
const dataHolderTest = dataSet2;
let firstWeekTest = dataHolderTest[0];
const weekOneTeamsTest = firstWeekTest.slice(0, depth);
for (const weekOneTeamTest of weekOneTeamsTest) {
let secondWeekTest = dataHolderTest[1];
newWinPercent = weekOneTeamTest.win_percent * newWinPercent;
newSelections.push(weekOneTeamTest.team);
for (const team2 of secondWeekTest) {
removeAllSelectedTeams(newSelections, secondWeekTest, team2);
}
}
console.log(dataSet2);
};
const removeAllSelectedTeams = (selections, dataHolder, team) => {
if (selections.includes(team.team)) {
const currentTeam = dataHolder.indexOf(team);
dataHolder.splice(currentTeam, 1);
}
return dataHolder;
};
I've been picking through this for a while now and it seems like the removeAllSelectedTeams
function is the problem.我已经仔细研究了一段时间,似乎
removeAllSelectedTeams
function 是问题所在。
Still I don't understand how my dataSet2
is being altered without calling the hook setDataSet2
我仍然不明白如何在不调用挂钩
setDataSet2
的情况下更改我的dataSet2
If you want to make a copy of an array or an object, you need to do it like this.如果你想复制一个数组或一个 object,你需要这样做。
listTwo = [...listOne]
or ObjectTwo = {...ObjectOne}
. listTwo = [...listOne]
或ObjectTwo = {...ObjectOne}
。 Simply using =
and not using the spread operator does not make a copy of that array or object for you, rather gives you another reference to the same array or object.简单地使用
=
而不使用展开运算符不会为您复制该数组或 object,而是为您提供对同一数组或 object 的另一个引用。
Try copying the array to dataHolderTest
instead of assigning it equal to dataSet2
with the spread operator ...
尝试将数组复制到
dataHolderTest
而不是使用扩展运算符将其分配为等于dataSet2
...
This way your not changing the original dataSet2
variable when interacting with dataHolderTest
这样您在与
dataHolderTest
交互时不会更改原始dataSet2
变量
const dataHolderTest = [...dataSet2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.