【问题标题】:react conditional render with ternary operator用三元运算符反应条件渲染
【发布时间】:2020-09-02 14:20:13
【问题描述】:

当屏幕首次加载时,我从服务器获取一些信息并设置状态。如果用户使用选择菜单并选择了其他东西,它会改变状态。

所以,我基本上想说的是,如果状态值来自服务器,则显示该状态值,或者如果状态值来自用户选择,请使用它。我也在尝试使用 && 来确保首先有一个可用的值。

const [country, setCountry] = useState();

useEffect(() => {
   // get location via public IP lookup and set state of country c 
   //calling code based on IP eg: +44
   setCountry(countryInfo.data);
 }, []);

<Input
name="countryCode"
placeholder={
country && country.location.calling_code ? country.location.calling_code : country.callingCode }
width="20%"
editable={false}
/>

<CountryPicker
  name="country"
  theme={{ fontSize: 14, padding: 30 }}
  countryCode={
    country && country.country_code
      ? country.country_code
      : country && country.cca2
  }
  withCallingCode
  withFilter
  withCountryNameButton={true}
  withFlagButton={false}
  withFlag={false}
  withEmoji={false}
  onSelect={(country) => setCountry(country)}
/>

country.location.calling_code 在初始加载时来自服务器,country.callingCode 是如果用户决定通过下拉列表更改它。

我得到的错误是:

undefined 不是对象(评估 country.location.calling_code)

【问题讨论】:

  • 看看这个组件的其余相关代码会很有帮助。
  • 最后有一个重复的: country.callingCode,这是错字吗?
  • 对不起,是的。我现在删除了一个副本
  • 在访问 calling_code 之前,您正在检查 country 但不是 country.location。真的有location 属性吗?
  • 另外,您应该包含minimal reproducible example,如果我们无法重现我们这边的问题,我们将无法真正帮助您。你是如何设置状态的?它是如何传递给这个组件的?等等

标签: javascript reactjs


【解决方案1】:

你可以先用这个拖把形状

country && country.location && country.location.calling_code ? country.location.calling_code : country.callingCode

或者这个形状它认为这个形状适合打字稿

country?.location?.calling_code ? country.location.calling_code : country.callingCode

witch 的意思是 if ?找到的项目移动到属性

【讨论】:

  • 谢谢,我试过了,报错:undefined is not an object(country.callingCode)
【解决方案2】:

位置也可能不存在,因此请检查以确保它存在。

country &amp;&amp; country.location &amp;&amp; country.location.calling_code ? country.location.calling_code : country &amp;&amp; country.callingCode || ""

country?.location?.calling_code ? country.location.calling_code : country?.callingCode || ""

【讨论】:

  • 谢谢,我试过了,报错:undefined is not an object(country.callingCode)
  • 这意味着国家是未定义的,所以你需要给一个默认值。我编辑了我的答案。
  • 因此,如果尚未定义国家/地区,则添加 || "" 只会使其成为空字符串,直到获得值为止。
  • 感谢您的坚持。但仍然出现错误,undefined is not an object(country.callingCode)
  • 对不起,我的错误,您需要再次检查国家/地区。