作为在浏览器中输入http://localhost:3000/ui/?goto=/ui/entity/e2
的示例,我想转到实体组件e2。
这是我的路由器:
<Route path="/ui/" component={App}>
<IndexRoute component={EntitiesPage} />
<Route component={Entity} path="entity/:id" />
<Route component={NotFound} path="*" />
</Route>
这是App组件:
import React from 'react'
const App = React.createClass( {
render() {
let gotoUrl = this.props.location.query.goto;
if (gotoUrl) {
// go here: gotoUrl;
} else {
return (
<div className="App">
{this.props.children}
</div>
)
}
}
})
export default App
this.context为空。 this.props有:
更新: 我最终使用了这个:
import React from 'react'
import { withRouter } from 'react-router'
const App = React.createClass( {
componentWillMount() {
let gotoUrl = this.props.location.query.goto;
if (gotoUrl) {
this.props.router.replace(gotoUrl);
}
},
render() {
return (
<div className="App">
{this.props.children}
</div>
);
}
})
export default withRouter(App)
答案 0 :(得分:0)
您应该使用browserHistory
import { browserHistory } from 'react-router';
...
if (gotoUrl) {
browserHistory.push(gotoUrl)
}
让我知道这是否有效
答案 1 :(得分:0)
可能绊倒你的一件事是 render
应该没有副作用。
“副作用”是指改变应用程序中正在发生的事情的任何事情:更新状态,进行AJAX调用,或者在这种情况下,更改页面位置。 render
方法只应从组件的当前状态读取,然后返回值。
因为您已经在使用React.createClass
,所以处理此问题的最佳方法是添加一个React专门处理的单独方法:componentWillMount
。我建议你把你的“重定向”逻辑放在这里。
为了正确更改页面位置,您需要访问react-router
操作的浏览器历史记录对象。您可以从react-router
库本身导入它,并直接调用它上面的方法:
// At top of file
import { browserHistory } from 'react-router'
// Then, in your component:
componentWillMount() {
let gotoUrl = this.props.location.query.goto;
if (gotoUrl) {
// NOTE: this may have security implications; see below
browserHistory.push(gotoUrl);
}
}
来源:documentation。
我建议您不要使用query.goto
,而是选择一个可以轻松验证的参数,例如实体ID本身(一个简单的正则表达式可以确保它有效)。否则,不道德的用户可能会向另一个用户发送链接,并导致他们访问他们并不意味着的页面。
*注意:那里有更严格的“副作用”定义,但这对于React开发非常有用。