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

两盒软妹~` 提交于 2019-12-03 11:40:27

问题


I'm new to React and I've made a navbar that displays the users name user

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

but the problem is if the user is not signed in, I get an error due to this.state.name being undefined. Is there some way I can check if this.state.name is defined before rendering it as part of the navbar or is there a better way to get rid of this error?


回答1:


Sure, use a ternary:

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

or even shorter

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



回答2:


Sure you can:

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

Now you can use userNavItem on your navbar component, and it will render only if this.state.name is defined.




回答3:


In React, you can check if a state exists before push

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


来源:https://stackoverflow.com/questions/39837893/react-can-i-check-if-a-state-exists-before-rendering-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!