Javascript reactjs - 无法读取未定义的属性推送

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36467126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:07:21  来源:igfitidea点击:

reactjs - can not read property push of undefined

javascriptreactjsreact-router

提问by angry kiwi

I have this code. What I want to do is when I click a button 'feature' it will take me to index route. However, React keeps saying 'can not read property push of undefined' What I've done wrong?

我有这个代码。我想要做的是当我单击“功能”按钮时,它会将我带到索引路线。但是,React 一直说“无法读取未定义的属性推送”我做错了什么?

route.js

路由.js

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

import Layout from "./page/Layout";
import Features from "./page/Features";
import Features from "./page/archive";

const app = document.getElementById('app');

ReactDOM.render(
    <Router history={hashHistory}>
        <Route path="/" component={Layout}>
            <IndexRoute component={Features} />
            <Route path="archive" component={Archive} />
        </Route>
    </Router>, app);

Layout component

布局组件

import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
    navigate(){
        this.context.router.push('/');
    }
    render(){ 
        return(
            <div>
                {this.props.children}
                <button onClick={this.navigate.bind(this)}>feature</button>
            </div>
        )
    }
}

package.json - partial

package.json - 部分

"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.1"
 "history": "^2.0.1",

-------------update to jordan's answer-------------

-------------更新乔丹的回答-------------

采纳答案by angry kiwi

export default class Layout extends React.Component{

    navigate = () => {
        this.context.router.push('/');
    }
    render(){ 
        return(
            <div>
                {this.props.children}
                <button onClick={this.navigate.bind(this)}>feature</button>
            </div>
        )
    }
}
Layout.contextTypes = {
    router: PropTypes.object.isRequired
}

回答by Wylliam Judd

In React Router v4, you no longer have to give a history to your router. Instead you just use BrowserRouteror HashRouterfrom 'react-router-dom'. But that makes it unclear how to push a rout to your history when you aren't in a react component.

在 React Router v4 中,您不再需要为路由器提供历史记录。相反,您只需使用BrowserRouterHashRouter来自'react-router-dom'。但这使得当您不在反应组件中时不清楚如何将溃败推向您的历史记录。

The solution is to use the historypackage.

解决方案是使用历史包。

Just import createHistorylike this:

只需createHistory像这样导入:

import createHistory from 'history/createBrowserHistory'

Or the way I do it is like this:

或者我这样做的方式是这样的:

import { createHashHistory } from 'history'

then create your history

然后创建你的历史

export const history = createHashHistory()

and now you can push to it:

现在你可以推动它:

history.push('/page')

I hope this helps others who come to this question. None of the current answers gave me what I needed.

我希望这可以帮助其他人提出这个问题。目前的答案都没有给我我需要的。

回答by Prayag

This may not be referring to above example but I had the same error. After lot of debugging I figured out that history is not reachable to my inner components. Make sure your history is reachable.

这可能不是指上面的例子,但我有同样的错误。经过大量调试后,我发现我的内部组件无法访问历史记录。确保您的历史记录可访问。

//main.js

//main.js

<BrowserRouter>
    <div>
        <Route path="/" component={Home}/>
        <Route path="/techMap" component={TechMap}/>
    </div>
 </BrowserRouter>

//app.js

//app.js

<div>
   <TechStack history= {this.props.history}/>
</div>

//techstack.js

//技术栈.js

<div>
    <span onClick={this.search.bind(this)}>
    </span>
 </div>
)

search(e){
 this.props.history.push('/some_url');
}

TechStack is my inner component.

TechStack 是我的内部组件。

Earlier I was able to get history in app.js but not in tech.js. But after passing props in form of history, I got the history in tech.js and routing works

早些时候,我可以在 app.js 中获取历史记录,但在 tech.js 中却无法获取。但是在通过历史形式的道具后,我在tech.js和路由工作中得到了历史

回答by Aaleks

You need to change your route.js page to

您需要将 route.js 页面更改为

import {Router, browserHistory} from 'react-router';

ReactDOM.render(
    <Router history={browserHistory}>
        <Route path="/" component={Layout}>
            <IndexRoute component={Features} />
            <Route path="archive" component={Archive} />
        </Route>
    </Router>, app);

And then everywhere you want to navigate you can use

然后你可以在任何你想要导航的地方使用

 import {Router, browserHistory} from 'react-router';

 browserHistory.push('/');

The react-router docs encourage you to use browserHistory instead of hashHistory

react-router 文档鼓励您使用 browserHistory 而不是 hashHistory

hashHistory uses URL hashes, along with a query key to keep track of state. hashHistory requires no additional server configuration, but is generally less preferred than browserHistory.

hashHistory 使用 URL 散列和查询键来跟踪状态。hashHistory 不需要额外的服务器配置,但通常不如 browserHistory 首选。

回答by hellogoodnight

I use browserHistory instead of HashHistory. Then I just need to do the following:

我使用 browserHistory 而不是 HashHistory。然后我只需要执行以下操作:

import { browserHistory } from 'react-router'
// ...
// ...

   navigate(){
        browserHistory.push('/');
    }

回答by Vishal Gulati

With React router v4, you need to wrap the components in withRouter. Then you can access history in your components. Do the following:

使用 React router v4,您需要将组件包装在 withRouter 中。然后您可以访问组件中的历史记录。请执行下列操作:

import { withRouter } from 'react-router-dom';
...
...
export default withRouter(MyComponent);

回答by Odeyinka Olubunmi

You don't need to use browserHistory anymore. React-router-dom inject into your component route related props and context. One of this props is 'history' and on this history object is a function push that you can call and pass the route you want to navigate to.

您不再需要使用 browserHistory。React-router-dom 注入到您的组件路由相关的道具和上下文中。其中一个道具是'history',在这个history 对象上是一个函数push,你可以调用它并传递你想要导航到的路线。

example in a Class base component, you can create a function like below as an onClick handler to redirect to specific link

例如,在 Class 基础组件中,您可以创建一个如下所示的函数作为 onClick 处理程序以重定向到特定链接

redirectToPage() {
 this.props.history.push('/page'); OR
 this.context.router.history.push('/page');
}

while in a function base stateless component

在基于函数的无状态组件中

redirectToSessionStatePage() {
 props.history.push('/page');OR
 context.router.history.push('/page');
}

回答by Aditya Singh

Change your Layout component to have navigate assigned to ES6 lambda. This is needed to set the correct value of this

更改您的布局组件以将导航分配给 ES6 lambda。这是设置正确值所必需的

import React from "react";
import {Link, Router, Route, hashHistory} from "react-router";
export default class Layout extends React.Component{
    navigate = () => {
        this.context.router.push('/');
    }

    render(){ 
      return(
        <div>
            {this.props.children}
            <button onClick={this.navigate.bind(this)}>feature</button>
        </div>
      )
    }
}

回答by doubledherin

It looks like you overwrote your Features import with whatever is in your /archives directory. In the code you posted, you have this:

看起来您用 /archives 目录中的任何内容覆盖了您的功能导入。在您发布的代码中,您有:

import Features from "./page/Features";
import Features from "./page/archive";

回答by Amit Maurya

import {withRouter} from 'react-router-dom';

从'react-router-dom'导入{withRouter};

export default withRouter(AppName);

导出默认 withRouter(AppName);