Javascript 在不使用重定向或链接的情况下更改 react-router v4 中的 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42271877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:01:44  来源:igfitidea点击:

Changing the URL in react-router v4 without using Redirect or Link

javascriptreact-routermaterial-uireact-router-v4

提问by Alex

I'm using react-router v4and material-uiin my React app. I was wondering how to change the URL once there is a click on a GridTilewithin GridList.

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

My initial idea was to use a handler for onTouchTap. However, the only way I can see to redirect is by using the components Redirector Link. How could I change the URL without rendering those two components?

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

I've tried this.context.router.push('/foo')but it doesn't seem to work.

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

回答by Ayush Sharma

Try this,

尝试这个,

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

warningworks for versions prior to v4

警告适用于 v4 之前的版本

and

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

for v4 and above

V4及以上

回答by Jobsamuel

I'm using this to redirect with React Router v4:

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

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

Hope it work for you ;)

希望它对你有用;)

回答by icc97

React Router v4

反应路由器 v4

There's a couple of things that I needed to get this working smoothly.

我需要做几件事情才能顺利完成这项工作。

The doc page on auth workflowhas quite a lot of what is required.

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

However I had three issues

但是我有三个问题

  1. Where does the props.historycome from?
  2. How do I pass it through to my component which isn't directly inside the Routecomponent
  3. What if I want other props?
  1. 在什么地方props.history来的呢?
  2. 我如何将它传递给不直接位于Route组件内部的组件
  3. 如果我想要其他props怎么办?

I ended up using:

我最终使用了:

  1. option 2 from an answer on 'Programmatically navigate using react router'- i.e. to use <Route render>which gets you props.historywhich can then be passed down to the children.
  2. Use the render={routeProps => <MyComponent {...props} {routeProps} />}to combine other propsfrom this answer on 'react-router - pass props to handler component'
  1. 来自“使用反应路由器编程方式导航”的答案中的选项 2 - 即使用<Route render>哪个让您props.history可以将其传递给孩子。
  2. 使用render={routeProps => <MyComponent {...props} {routeProps} />}于其他组合props这个答案在“反应-路由器-通过道具来处理组件”

N.B. With the rendermethod you have to pass through the props from the Routecomponent explicitly. You also want to use renderand not componentfor performance reasons (componentforces a reload every time).

注意使用该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>
)

One of the confusing things I found is that in quite a few of the React Router v4 docs they use MyComponent = ({ match })i.e. Object destructuring, which meant initially I didn't realise that Routepasses down three props, match, locationand history

我发现的一个令人困惑的事情是,在相当多的 React Router v4 文档中,他们使用MyComponent = ({ match })ie Object destructuring,这意味着最初我没有意识到Route传递了三个道具matchlocationhistory

I think some of the other answers here are assuming that everything is done via JavaScript classes.

我认为这里的其他一些答案假设一切都是通过 JavaScript 类完成的。

Here's an example, plus if you don't need to pass any propsthrough you can just use component

这是一个例子,另外如果你不需要通过任何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>
    }
}

回答by Barton Young

This is how I did a similar thing. I have tiles that are thumbnails to YouTube videos. When I click the tile, it redirects me to a 'player' page that uses the 'video_id' to render the correct video to the page.

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

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

ETA: Sorry, just noticed that you didn't want to use the LINK or REDIRECT components for some reason. Maybe my answer will still help in some way. ; )

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