我在我的 React 应用程序中使用react-router v4和material-ui 。GridTile
我想知道在GridList中单击 a 后如何更改 URL 。
我最初的想法是为onTouchTap
. 但是,我可以看到重定向的唯一方法是使用组件Redirect
或Link
. 如何在不渲染这两个组件的情况下更改 URL?
我试过this.context.router.push('/foo')
了,但它似乎不起作用。
我在我的 React 应用程序中使用react-router v4和material-ui 。GridTile
我想知道在GridList中单击 a 后如何更改 URL 。
我最初的想法是为onTouchTap
. 但是,我可以看到重定向的唯一方法是使用组件Redirect
或Link
. 如何在不渲染这两个组件的情况下更改 URL?
我试过this.context.router.push('/foo')
了,但它似乎不起作用。
尝试这个,
this.props.router.push('/foo')
警告适用于 v4 之前的版本
和
this.props.history.push('/foo')
对于v4 及更高版本
我正在使用它来重定向React Router v4:
this.props.history.push('/foo');
反应路由器 v4
我需要做几件事才能使这项工作顺利进行。
auth 工作流程的文档页面有很多需要的内容。
但是我遇到了三个问题
props.history
?Route
组件props
怎么办?我最终使用:
<Route render>
哪个可以让您获得props.history
然后可以传递给孩子。render={routeProps => <MyComponent {...props} {routeProps} />}
组合props
注意使用该方法,您必须明确地render
通过组件中的道具。Route
您还想使用render
而不是component
出于性能原因(component
每次都强制重新加载)。
const App = (props) => (
<Route
path="/home"
render={routeProps => <MyComponent {...props} {...routeProps}>}
/>
)
const MyComponent = (props) => (
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
fakeAuth.signout(() => props.history.push('/foo'))
}}>Sign out</button>
)
我发现的一个令人困惑的事情是,在相当多的 React Router v4 文档中,他们使用了Object destructuringMyComponent = ({ match })
,这意味着最初我没有意识到传递了三个 props和Route
match
location
history
我认为这里的其他一些答案是假设一切都是通过 JavaScript 类完成的。
这是一个示例,如果您不需要通过任何示例,则props
可以使用component
class App extends React.Component {
render () {
<Route
path="/home"
component={MyComponent}
/>
}
}
class MyComponent extends React.Component {
render () {
/**
* @link https://reacttraining.com/react-router/web/example/auth-workflow
* N.B. I use `props.history` instead of `history`
*/
<button onClick={() => {
this.fakeAuth.signout(() => this.props.history.push('/foo'))
}}>Sign out</button>
}
}
这就是我做类似事情的方式。我有作为 YouTube 视频缩略图的图块。当我单击磁贴时,它会将我重定向到使用“video_id”将正确视频呈现到页面的“播放器”页面。
<GridTile
key={video_id}
title={video_title}
containerElement={<Link to={`/player/${video_id}`}/>}
>
ETA:抱歉,刚刚注意到您出于某种原因不想使用 LINK 或 REDIRECT 组件。也许我的回答仍然会在某种程度上有所帮助。; )