如何修复错误对象可能未定义使用反应和打字稿?



在条件中使用变量时,我得到的错误对象可能未定义。

下面是片段,

render = () => {
const value_to_check = 8 //got by some http request could be any number
return (
<>
{condition1 && condition2 && (
value_to_check < 1 ? null : ( //here is where i get the pycharm 
//error object could be undefined
<div1>something</div1>
))}
)
}

我该如何修复该错误。谢谢。

render = () => {
const value_to_check = 8 //got by some http request could be anything

return (
<>
{condition1 && condition2 && (
// value_to_check might be undefined and u still compare it with < 1.
value_to_check < 1 ? null : ( //here is where i get the pycharm 
//error object could be undefined
<div1>something</div1>
))}

// Solution ( Notes: I don't recommend the style below, it's hard to read)
{condition1 && condition2 && value_to_check && ( value_to_check < 1 ? null : <div>Something</div>)}
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

最新更新