我在Stack Overflow上看到过多个这样的问题,但是没有一个修复方法管用。 this.props.location.state
始终返回未定义。这是我的 AppContainer
、ExamplePageParent
和 ExamplePage
。
import {Router, Route, Switch} from "react-router-dom";
class AppContainer extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path="/page" component={Page}
<Route exact path="/examplePage" component={ExamplePage}/>
</Switch>
</Router>
)
}
}
//has mapStateToProps and mapDispatch to Props here
export default connect(mapStateToProps, mapDispatchToProps)(AppContainer);
--
class Page extends Component {
render() {
return(
<AnotherPage key=this.props.id>
);
}
}
// has mapStateToProps here (this.props.id comes from here)
export default connect(mapStateToProps, mapDispatchToProps)(Page);
--
class AnotherPage extends Component {
render() {
return(
<ExamplePageParent key=this.props.id>
);
}
}
// has mapStateToProps here (this.props.id comes from here)
export default connect(mapStateToProps, null)(AnotherPage);
--
class ExamplePageParent extends Component {
//pathName and dataPassed content filled, not relevant to question
render() {
return(
<Link
class={'link-styling'}
target="_blank"
rel="noreferrer"
to={{pathname: this.state.pathName, state: {dataPassed: true} }}
>
Click Me
</Link>
);
}
}
//has mapStateToProps here
export default connect(mapStateToProps, null)(ExamplePageParent);
--
import {withRouter} from "react-router";
class ExamplePage extends Component {
constructor(props) {
super(props);
//this has content:
console.log(this.props.location);
//undefined:
console.log(this.props.location.state);
}
render() {
return(
// do stuff
);
}
}
export default withRouter(ExamplePage);
props.location.state
究竟在哪里未定义?ExamplePage
组件被呈现在component
prop 上,因此路由 prop 被传递给它,并且它也被包装在withRouter
HOC 中,所以再次传递了路由 prop。这个传递路由状态的ExamplePageParent
是在哪里被呈现的? - Drew ReeseExamplePageParent
是路由Page
的第三个子组件,我已经将其添加在上面了。 - penguinPage
>AnotherPage1
>AnotherPage2
>ExamplePageParent
。但只有Page
有路由。 - penguinApp
组件和从Page
到ExamplePageParent
的所有页面组件。你使用的是哪个路由器?this.state.pathName
是否是你期望的路径值? - Drew Reesethis.state.pathName
是正确的路径值。 - penguinExamplePageParent
实际上是Page
的第二个子组件。因此,Page
>AnotherPage
>ExamplePageParent
。 - penguin