node.js - '你试图重定向到你当前所在的同一条路线:“/”'当使用带有状态的重定向组件时
问题描述
我正在尝试创建一个包含两个页面的小型演示应用程序,one
并且two
. 用户可以通过按下按钮从一个页面导航one
到另一个页面,但前提是第二个页面中的位置对象的状态包含一个属性。如果没有,则将用户重定向到.two
key
one
我遇到的问题是,当使用to 对象从重定向one
和传递状态到时two
,React Router 警告:
您尝试重定向到您当前所在的同一条路线:“/”
这对我来说没有意义,因为我试图将用户从/one
to 重定向到/two
,而不是/
to /two
。
应用程序.js
import React, { Component } from 'react';
import './App.css';
import { NavLink, Redirect, Route, BrowserRouter as Router, Switch } from 'react-router-dom';
const App = () => (
<Router>
<div className="App">
<ul>
<li>
<NavLink to="/one">One</NavLink>
</li>
<li>
<NavLink to="/two">Two</NavLink>
</li>
</ul>
<Switch>
<Route path="/one" component={One} />
<Route path="/two" component={Two} />
</Switch>
</div>
</Router>
);
class One extends Component {
constructor(props) {
super(props);
this.state = {
shouldRedirect: false,
};
this.redirect = this.redirect.bind(this);
}
redirect() {
this.setState({
shouldRedirect: true,
});
}
render() {
const { shouldRedirect } = this.state;
if (shouldRedirect) {
return (
// Replacing the below Redirect with the following corrects the error,
// but then I'm unable to pass state to the second page.
// <Redirect to="/two" />
<Redirect
to={{
pathName: '/two',
state: {
key: 'Some data.',
},
}}
/>
);
}
return (
<div>
<h3>This is the first page.</h3>
<button type="button" onClick={this.redirect}>Click me to go to page two.</button>
</div>
);
}
}
class Two extends Component {
constructor(props) {
super(props);
this.state = {
shouldRedirect: false,
};
this.redirect = this.redirect.bind(this);
}
componentWillMount() {
const { location } = this.props;
if (location.state && location.state.key) {
const { key } = location.state;
this.key = key;
} else {
this.redirect();
}
}
redirect() {
this.setState({
shouldRedirect: true,
});
}
render() {
const { shouldRedirect } = this.state;
if (shouldRedirect) {
return (
<div>
<p>You're being redirected to the first page because a key was not provided.</p>
<Redirect to="/one" />
</div>
);
}
return (
<div>
<h3>This is the second page.</h3>
<p>The key you provided was "{this.key}".</p>
</div>
);
}
}
export default App;
应用程序.css
.App {
text-align: center;
}
解决方案
您正在传递pathName
而不是pathname
. 这应该可以解决问题。代码沙箱
上的工作示例。
<Redirect
to={{
pathname: "/two",
state: {
key: "Some data."
}
}}
/>
推荐阅读
- c# - 将实体框架结果从视图模型绑定到视图
- python - 当旋转框数量减少时,如何删除 tkinter 输入框?
- python - 检索 XML 文件,解析数据并打印出来
- python-3.x - 为什么我的 MLP ROC_AUC 只绘制 3 个点
- javascript - 仅连接同一类别中的点(Highcharts)
- php - Laravel 5.7、php curl 和 WordPress 的连接问题
- sql - 在雪花中解析 JSON
- python - 如何在networkx可视化中为不同的节点集设置不同的标签选项?
- javascript - 如何使用 for 循环将 javascript 数组的元素打印到网页?
- r - 将纬度经度范围映射到R中的坐标值的简单方法?