Javascript this.props.history.push 适用于某些组件而不适用于其他组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43837212/
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
this.props.history.push works in some components and not others
提问by Rbar
I am trying to programmatically change pages using browserHistory.push. In one of my components, but not in a component that I embedded inside of that one.
我正在尝试使用browserHistory.push. 在我的一个组件中,但不在我嵌入到该组件中的组件中。
Does anyone know why my project is throwing the error below only for the child component but not for the parent component?
有谁知道为什么我的项目只为子组件而不是父组件抛出以下错误?
Cannot read property 'push' of undefined
无法读取未定义的属性“推送”
Parent Component
父组件
import React, {Component} from 'react';
import { browserHistory } from 'react-router';
import ChildView from './ChildView';
class ParentView extends Component {
constructor(props) {
super(props);
this.addEvent = this.addEvent.bind(this);
}
changePage() {
this.props.history.push("/someNewPage");
}
render() {
return (
<div>
<div>
<button onClick={this.changePage}>Go to a New Page!</button>
</div>
<ChildView /> // this is the child component where this.props.history.push doesn't work
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.user
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
setName: setName
}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(ParentView);
Child Component
子组件
import React, {Component} from 'react';
import { browserHistory } from 'react-router';
class ChildView extends Component {
constructor(props) {
super(props);
this.addEvent = this.addEvent.bind(this);
}
changePage() {
this.props.history.push("/someNewPage");
}
render() {
return (
<div>
<div>
<button onClick={this.changePage}>Go to a New Page!</button>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
user: state.user
};
}
function matchDispatchToProps(dispatch) {
return bindActionCreators({
setName: setName
}, dispatch)
}
export default connect(mapStateToProps, matchDispatchToProps)(ChildView);
Router
路由器
// Libraries
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { browserHistory } from 'react-router';
// Components
import NotFound from './components/NotFound';
import ParentView from './components/ParentView';
import ChildView from './components/ChildView';
import SomeNewPage from './components/SomeNewPage';
// Redux
import { Provider } from 'react-redux';
import {createStore} from 'redux';
import allReducers from './reducers';
const store = createStore(
allReducers,
window.devToolsExtension && window.devToolsExtension()
);
const routes = (
<Router history={browserHistory}>
<div>
<Provider store={store}>
<Switch>
<Route path="/" exact component={Home} />
<Route path="/parentView" component={ParentView} />
<Route path="/someNewPage" component={SomeNewPage} />
<Route path="/childView" component={ChildView} />
<Route component={NotFound} />
</Switch>
</Provider>
</div>
</Router>
);
export default routes;
As you can see, the components are virtually exactly the same except that the child one is inside the parent one.
如您所见,除了子组件位于父组件内部之外,组件几乎完全相同。
Note I have tried these approaches but they do not resolve the issue for me:
注意我已经尝试过这些方法,但它们并没有为我解决问题:
回答by Chaim Friedman
You answered your question in your question.
你在你的问题中回答了你的问题。
As you can see, the components are virtually exactly the same except that the child one is inside the parent one.
如您所见,除了子组件位于父组件内部之外,组件几乎完全相同。
The very fact that the component is nested one further is your issue. React router only injects the routing props to the component it routed to, but not to the components nested with in.
组件进一步嵌套的事实是您的问题。React router 只将路由 props 注入它路由到的组件,但不会注入到嵌套的组件中。
See the accepted answer to thisquestion. The basic idea is that you now need to find a way to inject the routing props to the child component.
You can do that by wrapping the child in a HOC withRouter.
请参阅此问题的已接受答案。基本思想是,您现在需要找到一种方法将路由道具注入到子组件中。您可以通过将孩子包装在 HOC 中来做到这一点withRouter。
export default withRouter(connect(mapStateToProps, matchDispatchToProps)(ChildView));
I hope this helps.
我希望这有帮助。
回答by Notorious
Using withRouter is fine, an alternative option is to pass the history as a prop from parent to child (without using withRouter), e.g:
使用 withRouter 很好,另一种选择是将历史作为道具从父级传递给子级(不使用 withRouter),例如:
Parent
家长
<SignupForm history={this.props.history}/>
Child
孩子
this.props.history.push('/dashboard');
回答by Zahid Hassan Shaikot
You Can try this
你可以试试这个
this.context.history.push('/dashboard')
or pass the history as a prop from parent to child component like
或将历史作为道具从父组件传递给子组件,例如
parent
父母
<SignupForm history={this.props.history}/>
child
孩子
this.props.history.push('/dashboard');
or withRouter
或者 withRouter
import { withRouter } from "react-router";
export default withRouter(connect(mapStateToProps, {
...
})(Header));
回答by Prashant Yalatwar
This is the problem of Nested Components. I was facing this issue in Header component. I wanted to redirect the page to home page on clicking the logo.
这就是嵌套组件的问题。我在 Header 组件中遇到了这个问题。我想通过单击徽标将页面重定向到主页。
this.props.history.pushwon't work in nested components.
this.props.history.push不适用于嵌套组件。
So Solution is to use withRouter.
所以解决方案是使用withRouter.
To Use withRouterjust copy paste Below 2 lines in Header(You can use it in your component) :
要使用withRouter仅复制粘贴 Header 中的 2 行以下(您可以在您的组件中使用它):
import { withRouter } from "react-router";
export default withRouter(connect(mapStateToProps, {
...
})(Header));
回答by jerryurenaa
If anyone is still facing similar issues please try to change the onClick to this
如果有人仍然面临类似的问题,请尝试将 onClick 更改为此
onClick={() => this.props.history.push("/dashboard")}
also if you are in a child component please use the <Redirect to="/dashboard"/>component
此外,如果您在子组件中,请使用该<Redirect to="/dashboard"/>组件

