如何解决使用react和typescript时出现的错误对象可能是未定义的?

问题描述 投票:0回答:1

当使用条件中的变量时,我得到错误的对象可能是undefined。

以下是代码段。

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>
        ))}
    )
}

如何解决这个错误,谢谢。

javascript reactjs typescript
1个回答
0
投票

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>
© www.soinside.com 2019 - 2024. All rights reserved.