React:我可以在渲染之前检查状态是否存在吗

React: Can I check if a state exists before rendering it

我是 React 的新手,我制作了一个显示用户名用户的导航栏

<NavItem eventKey={4} href="#">{this.state.name}</NavItem>

但问题是如果用户未登录,我会收到错误消息,因为 this.state.name 未定义。在将 this.state.name 呈现为导航栏的一部分之前,有什么方法可以检查它是否已定义,或者是否有更好的方法来消除此错误?

当然,使用三元:

render() {
  return (
    this.state.name ? <NavItem>{this.state.name}</NavItem> : null
  );
}

甚至更短

render() {
  return (
    this.state.name && <NavItem>{this.state.name}</NavItem>
  );
}

当然可以:

let userNavItem
if (this.state.name !== undefined) {
  userNavItem = <NavItem eventKey={4} href="#">{this.state.name}</NavItem>
} else {
  userNavItem = null
}

现在您可以在导航栏组件上使用 userNavItem,只有定义了 this.state.name 才会呈现。

在 React 中,你可以在推送之前检查状态是否存在

    checkedProduct=(prop)=>{
  var checkIfExist = this.state.checkedProduct.filter((product)=>{
    return product===prop
  })
  if(checkIfExist.length>0){
    var checkIfExist = this.state.checkedProduct.filter((product)=>{
      return product!==prop
    })
    this.setState({ checkedProduct:checkIfExist })

  }else{
    this.setState({ checkedProduct: this.state.checkedProduct.concat(prop) })
  }
}