【发布时间】:2019-09-01 12:22:05
【问题描述】:
我有一个看起来像这样的组件(非常简化的版本):
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 函数吗?最好能解释一下修复工作的原因。
【问题讨论】:
标签: javascript reactjs react-hooks