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

时间:2017-02-16 10:55:03

标签: javascript react-router material-ui react-router-v4

我在我的React应用中使用react-router v4material-ui。我想知道如果在GridList内点击GridTile后如何更改网址。

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

我已经尝试this.context.router.push('/foo'),但它似乎无法运作。

4 个答案:

答案 0 :(得分:42)

试试这个,

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

警告 适用于v4之前的版本

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

v4及以上

答案 1 :(得分:35)

我正在使用此功能重定向 React Router v4

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

希望它对你有用;)

答案 2 :(得分:3)

  

React Router v4

为了让这项工作顺利进行,我需要做几件事。

auth workflow上的文档页面有很多内容。

但是我有三个问题

  1. props.history来自哪里?
  2. 如何将其传递给不直接位于Route组件
  3. 内的组件
  4. 如果我想要其他props怎么办?
  5. 我最终使用了:

      来自an answer on 'Programmatically navigate using react router'
    1. 选项2 - 即使用<Route render>来获取props.history,然后将其传递给孩子们。
    2. 使用render={routeProps => <MyComponent {...props} {routeProps} />}结合this answer on 'react-router - pass props to handler component'
    3. 中的其他props

      N.B。使用render方法,您必须明确地从Route组件传递道具。出于性能原因,您还希望使用render而非componentcomponent每次强制重新加载。)

      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文档中,他们使用MyComponent = ({ match })Object destructuring,这意味着我最初没有意识到Route向下传递三个道具,matchlocationhistory

      我认为这里的其他一些答案假设一切都是通过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>
          }
      }
      

答案 3 :(得分:0)

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

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

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

相关问题