【问题标题】:react and react-router context undefinedreact 和 react-router 上下文未定义
【发布时间】:2017-04-28 06:29:20
【问题描述】:

我正在尝试从一条路线导航到另一条路线,就像我设置路线的方式:

App.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';

// Pages
import Layout from './pages/Layout/Layout';
import Home from './pages/Home/Home';
import CityOverview from './pages/CityOverview/CityOverview';
import Game from './pages/Game/Game';

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path='/' component={Layout}>
            <IndexRoute component={Home}></IndexRoute>
            <Route path='/city-overview' component={CityOverview}></Route>
            <Route path='/game' component={Game}></Route>
        </Route>
    </Router>,
    document.getElementById('app')
);

然后我尝试在这个类中进行导航:

import React from 'react';

class MyComponent extends React.Component {

    constructor () {
        super();
        this.state = {
            email : '',
            password : ''
        };
    }

    render () {
        // ...
    }

    navigate () {

        this.context.router.push('/city-overview');

    }

}

MyComponent.contextTypes = {
    router: React.PropTypes.object.isRequired
};

export default MyComponent;

但是当它运行时,我得到一个“上下文未定义错误”...

【问题讨论】:

    标签: javascript reactjs ecmascript-6 react-router


    【解决方案1】:

    您需要将导航函数绑定到适当的上下文,以便其中的 this 关键字引用 React 类而不是函数。你可以使用箭头函数来做同样的事情。

    navigate = () => {
    
        this.context.router.push('/city-overview');
    
    }
    

    或者在构造函数中绑定它

    constructor () {
            super();
            this.state = {
                email : '',
                password : ''
            };
            this.navigate = this.navigate.bind(this);
        }
    

    【讨论】:

      【解决方案2】:

      使用“道具”而不是“上下文”

      this.props.router.push("city-overview");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-31
        • 2017-10-04
        • 2017-08-08
        • 1970-01-01
        • 2018-05-02
        • 2020-09-29
        • 2020-09-18
        • 1970-01-01
        相关资源
        最近更新 更多