React Native TypeScript useEffect 不更新数组
我正在尝试使用 Pusher、Typescript 和 React Native 创建实时投票,但候选人数组没有更新并显示在 useEffect 函数上。但是当我从正常投票中运行相同的代码行时,它可以工作(候选人数组已更新并正确显示);
const [candidates, setCandidates] = useState([]);
const vote = (id, position, name, name2) => {
var newVoteData = ({ voterName: votingData.voterName, voterId: votingData.voterId, position: position, candidateId: id, candidateName: name });
setProcessingModal(true);
fetch("http://172.20.10.4:8000/mobile/vote", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newVoteData),
})
.then((response) => response.json())
.then((data) => {
if (data.status == "ok") {
// This block of code works, updates the particular
// candidate voteCount and setCandidates correctly
setProcessingModal(false);
alert("Yay!!! , you have successfully voted");
const updatedData = candidates.map(x => (x.id === id ? { ...x, voteCount: data.voteCount } : x)); //updates votecount on candidate
let newArr = updatedData.sort((x, y) => {
return y.voteCount - x.voteCount;
});
setCandidates(updatedData);
} else {
setProcessingModal(false);
alert(data);
}
})
.catch((error) => {
setProcessingModal(false);
alert(error);
console.error("Error:", error);
});
};
下面的 useEffect 函数是有问题的地方,由于某种原因数组没有被更新
useEffect(() => {
const liveUpdateCandidates = (id, voteCount) => {
alert(voteCount);
const updatedData = candidates.map(x => (x.id === id ? { ...x, voteCount: voteCount } : x));//updates votecount on candidate does not work here
console.log("afer");
let newArr = updatedData.sort((x, y) => {
return y.voteCount - x.voteCount;
});
setCandidates(newArr);
};
//Pusher.logToConsole = true;
const pusher = new Pusher("3580cab8bee36d295917", {
cluster: "eu",
encrypted: true,
});
const channel = pusher.subscribe("votebooth-channel");
channel.bind("App\\Events\\BoothEvent", function(data) {
liveUpdateCandidates(data.candidateId, data.voteCount);
});
return (() => {
pusher.unsubscribe("votebooth-channel");
// pusher.unsubscribe('channel_name2');
});
}, [candidates]);
下面是返回数组的示例
[
{ "id": "3", "name": "Kwaku", "candidateUserId": null, "gender": "Male", "philosophy": "Good", "voteCount": "132" },
{ "id": "22", "name": "rose", "candidateUserId": null, "gender": "Female", "philosophy": "Php", "voteCount": "1" },
];
Am trying to create a real time voting using Pusher, typescript and react native, but the candidates array is not being updated and displayed on the useEffect function. but when I run the same code lines from a normal vote it works (the candidates array is updated and displayed correctly);
const [candidates, setCandidates] = useState([]);
const vote = (id, position, name, name2) => {
var newVoteData = ({ voterName: votingData.voterName, voterId: votingData.voterId, position: position, candidateId: id, candidateName: name });
setProcessingModal(true);
fetch("http://172.20.10.4:8000/mobile/vote", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newVoteData),
})
.then((response) => response.json())
.then((data) => {
if (data.status == "ok") {
// This block of code works, updates the particular
// candidate voteCount and setCandidates correctly
setProcessingModal(false);
alert("Yay!!! , you have successfully voted");
const updatedData = candidates.map(x => (x.id === id ? { ...x, voteCount: data.voteCount } : x)); //updates votecount on candidate
let newArr = updatedData.sort((x, y) => {
return y.voteCount - x.voteCount;
});
setCandidates(updatedData);
} else {
setProcessingModal(false);
alert(data);
}
})
.catch((error) => {
setProcessingModal(false);
alert(error);
console.error("Error:", error);
});
};
the below useEffect function is where am having issues, the array for some reason is not being updated
useEffect(() => {
const liveUpdateCandidates = (id, voteCount) => {
alert(voteCount);
const updatedData = candidates.map(x => (x.id === id ? { ...x, voteCount: voteCount } : x));//updates votecount on candidate does not work here
console.log("afer");
let newArr = updatedData.sort((x, y) => {
return y.voteCount - x.voteCount;
});
setCandidates(newArr);
};
//Pusher.logToConsole = true;
const pusher = new Pusher("3580cab8bee36d295917", {
cluster: "eu",
encrypted: true,
});
const channel = pusher.subscribe("votebooth-channel");
channel.bind("App\\Events\\BoothEvent", function(data) {
liveUpdateCandidates(data.candidateId, data.voteCount);
});
return (() => {
pusher.unsubscribe("votebooth-channel");
// pusher.unsubscribe('channel_name2');
});
}, [candidates]);
Below is a sample of the returned array
[
{ "id": "3", "name": "Kwaku", "candidateUserId": null, "gender": "Male", "philosophy": "Good", "voteCount": "132" },
{ "id": "22", "name": "rose", "candidateUserId": null, "gender": "Female", "philosophy": "Php", "voteCount": "1" },
];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可以解决一些问题。
首先,您使用的是
cantivates
作为依赖性和使用setCandidates
内部的使用效率。使用效应中的依赖项意味着每次依赖关系值都会触发。这意味着使用效应将进入一个循环,它很可能会崩溃,并且无效
。您应该删除它。
最后,您的代码需要一些重构。尝试对侦听器使用一种使用效果,而另一个使用效率来更新数据。另外,如果它有几行,我将其提取到具有清晰名称的功能。
There are a few things here I would fix.
First of all you are using a useEffect which has
candidates
as a dependency and usingsetCandidates
inside of that useEffect. Dependencies in a useEffect mean it will trigger everytime the dependency value changes.This means that the useEffect will enter into a loop and it will most likely crash and nothing will work.
Secondary, you are defining a value for
newArr
which is never being used, you should remove that.Finally, your code needs some refactoring. Try using one useEffect for the listener and another for the updating of data. Also, if it has several lines I would extract it to a function with a clear name of what it's doing.
似乎由于某种原因将ID变量发送到LiveUpDateCandidates函数作为字符串发送,因此我必须首先将其转换为int。如下
It appears the id variable is sent to liveUpdateCandidates function for some reason is been sent as string so I had to convert it to int first. like below