我在React: render more hooks中收到错误。我检查了其他帖子,这些帖子使用带有react钩子的条件句,但我无法在我的代码中诊断出类似的问题。如果我在challenges.js中注释掉代码的Object.keys部分,错误不会显示,但如果我把它留在里面,我会得到错误。我相信这是由keepsessionutils.js文件中的错误引起的。请协助。
challenges.js
return (
<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.js
export default function createChallengeUtil(playlist_id) {
// Check if there are at least 20 songs
var token = KeepSession();
// Populate Firebase with challenge data
}
keepsession.js
export 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
}
发布于 2020-04-01 06:19:32
你需要去看看React Hooks rules。
应用另一种方法会更好。此外,正如我所看到的,您在每次映射迭代中都调用KeepSession,但是您没有使用playlist_id来生成不同的钩子,因此它最终创建了一系列具有相同名称的钩子。
另外,最后,如果不使用这些钩子,也不从KeepSession()返回对它们的引用,那么在函数内部创建这些钩子的目的是什么?
发布于 2020-04-01 06:55:23
只要你的valid_playlists被修改了,你就会在线调用更多的钩子,所以当你的列表改变时,你调用钩子的时间也会改变。
React会记住调用的钩子和顺序。
试着改变一下你的方法。-使用钩子的任何非组件函数的名称useMyHook
。-请勿调用函数来创建侦听器onClick={doSomething()}
-请勿在处理程序内使用钩子createChallengeUtil
正在调用钩子
https://codesandbox.io/s/stack-react-hook-60960690-63yf2
我希望这种方法对你来说很好。
https://stackoverflow.com/questions/60960690
复制相似问题