50

我在我的 React 应用程序中使用react-router v4material-ui 。GridTile我想知道在GridList中单击 a 后如何更改 URL 。

我最初的想法是为onTouchTap. 但是,我可以看到重定向的唯一方法是使用组件RedirectLink. 如何在不渲染这两个组件的情况下更改 URL?

我试过this.context.router.push('/foo')了,但它似乎不起作用。

4

4 回答 4

86

尝试这个,

this.props.router.push('/foo')

警告适用于 v4 之前的版本

this.props.history.push('/foo')

对于v4 及更高版本

于 2017-02-16T11:09:22.853 回答
42

我正在使用它来重定向React Router v4

this.props.history.push('/foo');
于 2017-04-08T18:40:07.257 回答
7

反应路由器 v4

我需要做几件事才能使这项工作顺利进行。

auth 工作流程的文档页面有很多需要的内容。

但是我遇到了三个问题

  1. 从哪里来props.history
  2. 如何将它传递给不在组件内部的Route组件
  3. 如果我想要其他的props怎么办?

我最终使用:

  1. 选项 2 来自“使用反应路由器以编程方式导航”的答案- 即使用<Route render>哪个可以让您获得props.history然后可以传递给孩子。
  2. 使用'react-router - pass props to handler component' 的这个答案中的其他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和Routematchlocationhistory

我认为这里的其他一些答案是假设一切都是通过 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>
    }
}
于 2017-05-27T22:31:55.160 回答
1

这就是我做类似事情的方式。我有作为 YouTube 视频缩略图的图块。当我单击磁贴时,它会将我重定向到使用“video_id”将正确视频呈现到页面的“播放器”页面。

<GridTile
  key={video_id}
  title={video_title}
  containerElement={<Link to={`/player/${video_id}`}/>}
 >

ETA:抱歉,刚刚注意到您出于某种原因不想使用 LINK 或 REDIRECT 组件。也许我的回答仍然会在某种程度上有所帮助。; )

于 2017-07-20T18:21:54.237 回答