我有一个组件,如果它的加载状态为 true,则返回加载标记,如果 id 为 false,则返回其他内容。
但是我得到错误:
React Hook is called conditionally. React Hooks must be called in the exact same order in every component render.
解决此问题的正确方法是什么?
我的组件:
const store = React.useContext(StoreContext);
const [loading, setLoading] = useState(false)
if(loading) {
return <p>Loading...</p>
}
return useObserver(() => (
<div className="pa2">
<div className="flex">
{store.restaurantResults[store.selectedFood] &&
store.restaurantResults[store.selectedFood].map((rest, i) => {
return (
<div key={i} className="pa2">
<img src={rest.image_url} alt="restuarant" />
<p>Reviews{rest.review_count}</p>
</div>
);
})}
</div>
</div>
));
};```
由于useObserver()
是一个钩子,你必须在每次渲染中调用它,你不能有条件地跳过它。
一种选择是在钩子回调内移动条件,如果这是您的选项:
return useObserver(() => (
loading
? <p>Loading...</p>
: <div className="pa2">
<div className="flex">
{store.restaurantResults[store.selectedFood] &&
store.restaurantResults[store.selectedFood].map((rest, i) => {
return (
<div key={i} className="pa2">
<img src={rest.image_url} alt="restuarant" />
<p>Reviews{rest.review_count}</p>
</div>
);
})}
</div>
</div>
);
};