三元运算符?在 Javascript 中从预期向后解析
Ternary operator ? in Javascript is resolving backwards from expected
我有以下 React with Typescript 组件,它应该根据通过 Firebase auth 验证的用户来回切换:
const Navigation = (authUser: any) => (
<div>
{console.log(authUser)}
{authUser ? <NavigationAuth /> : <NavigationNonAuth /> }
<h1>Navigation</h1>
</div>
);
它上面的组件是 App,它在 authUser 属性 中的管道如下所示:
...
interface Props {
firebase?: Firebase,
listener?: any
}
interface State {
authUser: any,
}
class App extends React.Component<Props, State> {
listener: any;
constructor(props: any) {
super(props)
this.state = {
authUser: null
}
}
componentDidMount() {
this.listener = this.props.firebase?.auth.onAuthStateChanged(authUser => {
authUser
? this.setState({ authUser })
: this.setState({ authUser: null });
});
}
componentWillUnmount() {
this.listener();
}
render() {
return(
<Router>
<div>
<Navigation authUser={this.state.authUser}/>
<hr />
...
使用 React 开发人员工具,我可以从工具中看到 authUser 为空,因为我没有触发任何登录操作,但即使该值明确为空,它仍然等同于 {authUser ? <NavigationAuth /> : <NavigationNonAuth /> }
为真并呈现 <NavigationAuth />
而不是 `'
我的逻辑中是否遗漏了什么?或者我不知道三元运算符使用空值的一些时髦方式?我希望如果它是空值, false
结果将呈现,除非我现在编码的方式是以某种方式寻找除某种未定义之外的任何值?哪个 null 算作?因为它不是未定义的?
陌生人,如果我明确定义它,那么三元运算符就是这样:
{authUser != null ? <NavigationAuth /> : <NavigationNonAuth /> }
即使值为 null,它仍然呈现 <NavigationAuth />
。我做错了什么?
我对TypeScript不熟悉,但不应该是props.authUser吗?在 vanilla JS 中,我会这样写:
const Navigation = ({authUser}) => (
<div>
{console.log(authUser)}
{authUser ? <NavigationAuth /> : <NavigationNonAuth /> }
<h1>Navigation</h1>
</div>
);
我有以下 React with Typescript 组件,它应该根据通过 Firebase auth 验证的用户来回切换:
const Navigation = (authUser: any) => (
<div>
{console.log(authUser)}
{authUser ? <NavigationAuth /> : <NavigationNonAuth /> }
<h1>Navigation</h1>
</div>
);
它上面的组件是 App,它在 authUser 属性 中的管道如下所示:
...
interface Props {
firebase?: Firebase,
listener?: any
}
interface State {
authUser: any,
}
class App extends React.Component<Props, State> {
listener: any;
constructor(props: any) {
super(props)
this.state = {
authUser: null
}
}
componentDidMount() {
this.listener = this.props.firebase?.auth.onAuthStateChanged(authUser => {
authUser
? this.setState({ authUser })
: this.setState({ authUser: null });
});
}
componentWillUnmount() {
this.listener();
}
render() {
return(
<Router>
<div>
<Navigation authUser={this.state.authUser}/>
<hr />
...
使用 React 开发人员工具,我可以从工具中看到 authUser 为空,因为我没有触发任何登录操作,但即使该值明确为空,它仍然等同于 {authUser ? <NavigationAuth /> : <NavigationNonAuth /> }
为真并呈现 <NavigationAuth />
而不是 `'
我的逻辑中是否遗漏了什么?或者我不知道三元运算符使用空值的一些时髦方式?我希望如果它是空值, false
结果将呈现,除非我现在编码的方式是以某种方式寻找除某种未定义之外的任何值?哪个 null 算作?因为它不是未定义的?
陌生人,如果我明确定义它,那么三元运算符就是这样:
{authUser != null ? <NavigationAuth /> : <NavigationNonAuth /> }
即使值为 null,它仍然呈现 <NavigationAuth />
。我做错了什么?
我对TypeScript不熟悉,但不应该是props.authUser吗?在 vanilla JS 中,我会这样写:
const Navigation = ({authUser}) => (
<div>
{console.log(authUser)}
{authUser ? <NavigationAuth /> : <NavigationNonAuth /> }
<h1>Navigation</h1>
</div>
);