Javascript React:我可以在渲染之前检查状态是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39837893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React: Can I check if a state exists before rendering it
提问by jmona789
I'm new to React and I've made a navbar that displays the users name user
我是 React 的新手,我制作了一个显示用户名 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?
但问题是如果用户没有登录,我会因为 this.state.name 未定义而收到错误消息。有什么方法可以检查 this.state.name 在将它渲染为导航栏的一部分之前是否已定义,还是有更好的方法来摆脱这个错误?
回答by Scarysize
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>
);
}
回答by Mchl
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.
现在您可以userNavItem
在您的导航栏组件上使用,并且只有在this.state.name
定义时才会呈现。
回答by Rahul Jat
In React, you can check if a state exists before push
在 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) })
}
}