我在Stack溢出上看到了这些问题中的几个,但似乎没有一个修复方法有效。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);
发布于 2022-02-10 20:34:24
问题
Router
,它需要一个history
对象来使用定义的location
对象.要解决未定义的location
,您有几个选项:
history
包导入自定义历史记录创建者:从“历史”导入{ createBrowserHistory };const = createBrowserHistory();.
BrowserRouter
、HashRouter
、MemoryRouter
等.:将{ BrowserRouter作为路由器}从“react路由器-dom”导入;.
要解决访问接收组件中的"state“问题,您需要添加一些逻辑。当应用程序在一个新的窗口/选项卡中启动时,状态不会被传输,因此要解决这个问题,您可以将路由状态序列化为queryString搜索param。
<Link
className={"link-styling"}
target="_blank"
rel="noreferrer"
to={{
pathname: this.state.pathName,
search:
"stuff=content&moreStuff=moreContent" + // existing search params
"&dataPassed=This is the passed data.", // additional for state
state: { dataPassed: "This is the passed data." }
}}
>
Click Me
</Link>
然后在ExamplePage
进程中,queryString提取并删除添加的"dataPassed"
查询param,并使用先前存在的queryString填充路由状态重定向。
class ExamplePage extends Component {
componentDidMount() {
const { history, location } = this.props;
const { pathname, state, search } = location;
console.log({ location });
const searchParams = new URLSearchParams(search);
let dataPassed;
if (searchParams.has("dataPassed")) {
dataPassed = searchParams.get("dataPassed");
searchParams.delete("dataPassed");
}
history.replace({
pathname,
search: searchParams.toString(),
state: { dataPassed }
});
}
render() {
return (
...
);
}
}
https://stackoverflow.com/questions/71070641
复制相似问题