最佳答案
我有一个这样的组件(非常简化的版本) :
const component = (props: PropTypes) => {
const [allResultsVisible, setAllResultsVisible] = useState(false);
const renderResults = () => {
return (
<section>
<p onClick={ setAllResultsVisible(!allResultsVisible) }>
More results v
</p>
{
allResultsVisible &&
<section className="entity-block--hidden-results">
...
</section>
}
</section>
);
};
return <div>{ renderResults() }</div>;
}
当我加载这个组件所在的页面时,我得到了这个错误: Uncaught Invariant Violation: Rendered more hooks than during the previous render.
我试图找到这个错误的解释,但是我的搜索没有返回任何结果。
当我稍微修改组件时:
const component = (props: PropTypes) => {
const [allResultsVisible, setAllResultsVisible] = useState(false);
const handleToggle = () => {
setAllResultsVisible(!allResultsVisible);
}
const renderResults = () => {
return (
<section>
<p onClick={ handleToggle }>
More results v
</p>
{
allResultsVisible &&
<section className="entity-block--hidden-results">
...
</section>
}
</section>
);
};
return <div>{ renderResults() }</div>;
}
我不再得到那个错误。是因为我在由 renderResults
返回的 jsx 中包含了 setState
函数吗?如果能够解释为什么这个修复程序能够工作,那就太好了。