如何从nextjs的处理程序访问状态?

问题描述 投票:0回答:1

我有一个由自定义应用程序(_app)定义的处理程序,请转到routeChangeStart事件。

处理程序应分析新路径,并将一些结果存储在状态变量中。该处理程序是一个类成员,但是会引发错误:

未处理的拒绝(TypeError):未定义

这里是代码:

import App from 'next/app';
import Router from 'next/router'
import { withRouter } from 'next/router'
import MyAppContext from '~/components/MyAppContext';


class MyApp extends App {

    state = {
      language: null
    };

    getCurrentLanguage(url){
        ...
    }

    handleRouteChange(url){
      console.log('App is changing to: ', url)
      this.setState (  //throws: Unhandled Rejection (TypeError): this is undefined
         {language: this.getCurrentLanguage(url)}
      )
    }
    componentDidMount = () => {

      this.setState({language: this.getCurrentLanguage()})
        Router.events.on('routeChangeStart', this.handleRouteChange)
      };

    render() {
      const { Component, pageProps } = this.props;

      return (
        <MyAppContext.Provider value={{ language: this.state.language }}>
          <Component {...pageProps} />
        </MyAppContext.Provider>
      );
    }
  }

export default withRouter(MyApp)
javascript reactjs react-router next.js
1个回答
1
投票

该函数是一个类成员,但this取决于该函数被调用不是已声明的上下文。您正在将函数引用传递给侦听器,该侦听器将从其他地方调用它,这意味着this将不再引用该类。

您必须手动将其绑定到this,或使其成为箭头功能。

handleRouteChange = (url) => {

// or

Router.events.on('routeChangeStart', this.handleRouteChange.bind(this))
© www.soinside.com 2019 - 2024. All rights reserved.