[英]Conditionally render useEffect fetch React
Making a video game clip posting app.制作视频游戏剪辑发布应用程序。 I have a controller on the backend that will give me the clips in order of most commented on clips to least.我在后端有一个控制器,它将按照对剪辑的评论最多到最少的顺序为我提供剪辑。 I would like to switch between having the data ordered normally, to from most to least comments by using a select tag (later I will add more filters).我想在正常排序数据之间切换,使用选择标签从最多评论到最少评论(稍后我将添加更多过滤器)。 I was hoping I could conditionally render both of the fetches based on a state from the select tag onChange, but I got an error.我希望我可以根据选择标记 onChange 的状态有条件地渲染这两个提取,但我得到了一个错误。
Line 18:5: React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks
Line 24:5: React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render react-hooks/rules-of-hooks
this is my code.这是我的代码。 Note that I was just testing it with a boolean.请注意,我只是用布尔值测试它。
const boolean = true;
if (boolean == true) {
useEffect(() => {
fetch("/clips")
.then((r) => r.json())
.then((data) => setClipData(data));
}, []);
} else {
useEffect(() => {
fetch("/most_comments")
.then((r) => r.json())
.then((data) => setClipData(data));
}, []);
}
As the error says, you can't have useEffect
called conditionally.正如错误所说,您不能有条件地调用useEffect
。 Instead, call it a single time regardless, and inside that function, look to see whether you need to fetch the clips or the comments.相反,无论如何都调用它一次,然后在该函数中查看是否需要获取剪辑或评论。
useEffect(() => {
if (boolean) {
fetch("/clips")
.then((r) => r.json())
.then((data) => setClipData(data));
// don't forget to .catch errors here
} else {
fetch("/most_comments")
.then((r) => r.json())
.then((data) => setClipData(data)); // did you mean to call setCommentsData or something here?
// don't forget to .catch errors here
}
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.