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

时间:2020-03-03 21:29:10

标签: javascript reactjs react-router next.js

我有一个由自定义应用(_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)

1 个答案:

答案 0 :(得分:1)

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

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

handleRouteChange = (url) => {

// or

Router.events.on('routeChangeStart', this.handleRouteChange.bind(this))