React hooks 条件渲染
React hooks conditional render
我有一个使用自定义挂钩 useTimer 的功能性 React 组件。该组件从 API(通过 redux 存储)接收数据。
function RenderRespond(order) {
if(order === null) return;
const {
buyerName,
offerDuration,
} = order;
const {
seconds,
minutes,
} = useTimer(offerDuration);
return(
<div>
{BuyerName}
{minutes}:{seconds}
</div>
);
}
我只想在顺序不对时渲染这个组件null.The 代码抛出 hooks cannot be conditionally 的错误rendered.How 我可以实现这个吗?
您应该在 if 语句之前调用 useTimer
。
像这样:
function RenderRespond(order) {
const {
buyerName,
offerDuration = '', // not sure what the default value will be, but you can change it for your needs
} = order || {};
const {
seconds,
minutes,
} = useTimer(offerDuration);
if(order === null) return null;
return(
<div>
{BuyerName}
{minutes}:{seconds}
</div>
);
}
如果您查看 the docs 发生这种情况的原因是因为 if(order === null) return
将阻止调用挂钩,但它会期望它被调用;
观察
也许你打错了?
您正在破坏 buyerName
但渲染 BuyerName
(大写字母 B)。
我有一个使用自定义挂钩 useTimer 的功能性 React 组件。该组件从 API(通过 redux 存储)接收数据。
function RenderRespond(order) {
if(order === null) return;
const {
buyerName,
offerDuration,
} = order;
const {
seconds,
minutes,
} = useTimer(offerDuration);
return(
<div>
{BuyerName}
{minutes}:{seconds}
</div>
);
}
我只想在顺序不对时渲染这个组件null.The 代码抛出 hooks cannot be conditionally 的错误rendered.How 我可以实现这个吗?
您应该在 if 语句之前调用 useTimer
。
像这样:
function RenderRespond(order) {
const {
buyerName,
offerDuration = '', // not sure what the default value will be, but you can change it for your needs
} = order || {};
const {
seconds,
minutes,
} = useTimer(offerDuration);
if(order === null) return null;
return(
<div>
{BuyerName}
{minutes}:{seconds}
</div>
);
}
如果您查看 the docs 发生这种情况的原因是因为 if(order === null) return
将阻止调用挂钩,但它会期望它被调用;
观察
也许你打错了?
您正在破坏 buyerName
但渲染 BuyerName
(大写字母 B)。