我有一个组件,看起来像这样(非常简化的版本):
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
函数吗?能否解释一下这个修复方式的原理呢?
return
语句。 - jlhasson