在路由更改Next.js上更改状态

JavaScript React.js

Tony凯

2020-03-23

嗨,我要在next.js中切换导航,它工作正常,只是我希望导航在路线更改时再次关闭。

例如,如果我在主页上并切换导航,则导航将打开并显示指向“关于”页面的链接。如果单击该链接,将按预期进入“关于”页面-但导航仍处于打开状态!

我已经尝试了一些方法-我想我想利用onRouteChangeComplete(url),但是我正在努力更新navActive状态。

我的page.js文件:

class Page extends Component {
  state = {
    navActive: false
  };

  toggle = () => {
    this.setState({
      navActive: !this.state.navActive
     });
  };

  render() {
    return (
      <ThemeProvider theme={theme}>
        <StyledPage className="full-page-wrapper">
          <Meta />
          <Header navActive={this.state.navActive} toggle={this.toggle} />
          <PrimaryContent>{this.props.children}</PrimaryContent>
          <GlobalStyle />
        </StyledPage>
      </ThemeProvider>
    );
  }
}

然后是我的头文件:

class Header extends React.Component {
  render() {
    return (
      <HeaderSide

        <HeaderToggleBar onClick={() => this.props.toggle()} />

      </HeaderSide>
    );
  }
}

因此,应用程序以navActive状态为false开头,单击HeaderToggleBar元素将打开并关闭导航。但是,当路线改变时,我需要关闭导航。我想我可以将click事件放在标题内的导航项上(以便单击切换到新页面),但这似乎有点过头了。

谢谢。

第2947篇《在路由更改Next.js上更改状态》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
伽罗理查德 2020.03.23

我相信您需要绑定您的回调。您可能还需要添加一个构造函数。这是一个接受文件上传的项目的片段。

    class Files extends React.Component {
        // define your constructor and call super before setting state vars
        constructor(props){
            super(props);
            this.state = {
                uploadStatus: false
            }
            // Bind your callback
            this.handleUploadImage = this.handleUploadImage.bind(this);
            // set other initial vars if needed
        }

        handleUploadImage(files){
            // do stuff with the files
        }

        render () {
            return (
                <div id="fileContainer">
                    <MyDropzone id={this.props.project._id} onDrop={this.handleUploadImage}>
                        {({getRootProps}) => <div {...getRootProps()} />}
                    </MyDropzone>
                </div>
            )
        }
    }

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android