React tsx 函数没有收到值

React tsx function is not receiving value

我正在使用一个组件,它是一个 return 导航栏的函数,具体取决于用户是否正在登录,为此我需要向该函数传递一个参数。

index.js 总是调用 NavBar class

    render() {
    const isLogged: boolean = true as boolean;
    console.log("F isLogged " + isLogged);
    
    return (  
      <>
      <NavbarComponent {...false}/>
      <h2>It is {this.state.data}.</h2>
      </>
    );
  }

此 NavBar class 调用有问题的组件 NavbarComponent

export default function NavbarComponent(isLogged: boolean) {
  console.log("isLogged " + (isLogged as boolean));
  ...
    <div>
        <main
        className={clsx(classes.content, {
          [classes.contentShift]: open,
        })} />
        {isLogged == true ? 
          renderMenuLogged:
          renderMenuLogin}
    </div>
[Log] F isLogged true (2.chunk.js, line 63)
[Log] F isLogged true (2.chunk.js, line 63)
[Log] isLogged [object Object] (2.chunk.js, line 272)
[Log] isLogged [object Object] (2.chunk.js, line 272)
[Log] F isLogged true (2.chunk.js, line 63)
[Log] F isLogged true (2.chunk.js, line 63)
[Log] isLogged [object Object] (2.chunk.js, line 272)
[Log] isLogged [object Object] (2.chunk.js, line 272)

日志上发生了什么,当记录 F isLogged 时 return 为 true,但是当记录 NavBar 的 isLogged return 时为 [Object Object],当使用调试模式并检查有什么这个 var 是空的,就像 {...false} 永远不会去 NavbarComponent(isLogged: boolean)...有什么想法吗? :(

简短回答:

您在参数声明中缺少 {}。请注意, isLogged 不是功能组件的参数。 props 对象是参数:

export default function NavbarComponent({ isLogged: boolean }) {

长答案:

要使用 typescript 正确捕获错误,您应该开始使用正确的类型声明您的组件:

type NavbarProps = {
  isLogged: boolean
}

const NavbarComponent: React.FunctionComponent<NavbarProps> = ({ isLogged }) => {
  ...
};

export default NavbarComponent;

那会马上发现你的错误。