我有一个useState,如下:
const [Total, setTotal] = useState(props.location.state.data.price)
我想拥有它,如果props.location.state.data.price被定义,它将呈现,但是如果未定义,则它将返回0。
我尝试了无效的合并运算符,但是它不起作用。任何帮助表示赞赏。谢谢
答案 0 :(得分:5)
像这样:
const [Total, setTotal] = useState(props.location?.state?.data?.price ?? 0)
或类似这样:
const [Total, setTotal] = useState(
props.location &&
props.location.state &&
props.location.state.data &&
props.location.state.data.price || 0
)
答案 1 :(得分:1)
如果total
应该在某个时候改变,您可能还想更新props.location.state.data.price
,对吗?所以我会这样做的:
const [total, setTotal] = useState(0)
useEffect(() => {
if (!props.location?.state?.data?.price) {
setTotal(0);
return;
}
setTotal(props.location.state.data.price);
}, [props.location.state.data.price])