我收到 React 中的错误:渲染的钩子比上一次渲染时更多。我检查了其他帖子,这些帖子使用带有反应钩子的条件来解决,但我无法在我的代码中诊断出类似的问题。如果我在 challenge.js 中注释掉代码的 Object.keys 部分,则不会显示错误,但如果我将其留在其中,则会收到错误消息。我相信这是由 keepsessionutils.js 文件中的错误引起的。请协助。挑战.jsreturn ( <div className="about"> <div className="about-header"> <div className="about-headerText"> <h2> Dummy Challenge </h2> <h2> Dummy Challenge </h2> <h2> Dummy Challenge </h2> <h2> Dummy Challenge </h2> <h2> Dummy Challenge </h2> <hr /> {Object.keys(valid_playlists).map(key => ( <button type="button" onClick={createChallengeUtil(key)}> {valid_playlists[key]} </button> ))} </div> </div> </div> );}createChallengeUtil.jsexport default function createChallengeUtil(playlist_id) { // Check if there are at least 20 songs var token = KeepSession(); // Populate Firebase with challenge data}保持会话.jsexport default function KeepSession() { const [value, setValue] = React.useState( localStorage.getItem('myValueInLocalStorage') || '' ); // Here I am just checking to see if we need to retrieve a new token or not. if (value === "undefined"){ var token = getLocalToken(); } else{ var token = value; } // This block detects if the user refreshes the page and stores the current token if so. window.onbeforeunload = (e) => { // I'm about to refresh! do something... localStorage.setItem('myValueInLocalStorage', token) setValue(token); }; return token}
2 回答

墨色风雨
TA贡献1853条经验 获得超6个赞
您需要查看React Hooks 规则。
应用另一种方法会更好。此外,正如我所见,您在每次地图迭代时都调用 KeepSession,但您没有使用 playlist_id 生成不同的钩子,因此它最终创建了一堆具有相同名称的钩子。
此外,最后,如果您不使用这些 Hook,也不从 KeepSession() 返回对它的引用,那么在函数内部创建这些 Hook 的目的是什么?

慕妹3146593
TA贡献1820条经验 获得超9个赞
只要您的 valid_playlists 修改,您将在线调用更多挂钩,因此当您的列表更改时,将更改您调用挂钩的时间。
React 会记住调用的钩子和顺序。
试着改变一点你的方法。-useMyHook
使用钩子的任何非组件函数的名称。- 不要调用函数来创建侦听器onClick={doSomething()}
- 不要在处理程序中使用钩子createChallengeUtil
正在调用钩子
https://codesandbox.io/s/stack-react-hook-60960690-63yf2
我希望这种方法适合你。
添加回答
举报
0/150
提交
取消