简体   繁体   English

如何使用react-router来触发状态更改?

[英]How can I use react-router to trigger state changes?

I'm still coming to grips with React and react-router, but I'm wondering how to use react-router to simply update application state without re-rendering DOM nodes. 我仍然要处理React和react-router,但我想知道如何使用react-router简单地更新应用程序状态而无需重新呈现DOM节点。

For example, suppose I have: 例如,假设我有:

<Router history={browserHistory}>
  <Route path="/" component={App}>
    <IndexRoute screen="main" />
    <Route path="settings" screen="sync" />
    <Route path="overview" screen="overview" />
  </Route>
</Router>

I'd like to re-use react-router's matching but simply update the App component's current screen. 我想重新使用react-router的匹配,只需更新App组件的当前屏幕即可。

The reason is that suppose in the above example I have three screens arranged horizontally with only one visible at a time. 原因是假设在上面的例子中我有三个水平排列的屏幕,一次只能看到一个。 When the route changes I want to animate in the appropriate screen. 当路线改变时,我想在适当的屏幕中进行动画制作。 If I do that by assigning a component to each route, react-router doesn't render the other screens until the route matches, and there's a noticeable lag for the screen to slide in. 如果我通过为每个路由分配一个组件来做到这一点,则在路由匹配之前,react-router不会呈现其他屏幕,并且屏幕滑入会有明显的延迟。

However, if I keep all three screens in the DOM and simply toggle state to trigger CSS transitions there is no lag (since, with appropriate use of will-change , the browser can pre-render the off-screen layer). 但是,如果我将所有三个屏幕保留在DOM中并且只是切换状态以触发CSS转换,则没有延迟(因为,通过适当使用will-change ,浏览器可以预渲染屏幕外层)。

I've tried half a dozen ways of achieving this but they're all very hacky or involve duplicating the matching code somewhat. 我已经尝试了六种方法来实现这一点,但它们都非常hacky或涉及重复匹配代码。 What am I doing wrong? 我究竟做错了什么?

Also, I'd like to avoid adding something like Redux just to fix this if possible. 此外,我想避免添加像Redux这样的东西来解决这个问题。

So you want something similar to Spectacle ? 所以你想要类似Spectacle的东西?

In your case I would place all the screens as children of the App component, and use react-router's params to know which screen you're on. 在您的情况下,我会将所有屏幕作为App组件的子项,并使用react-router的参数来了解您所在的屏幕。

<Route path="/(:screen)" component={App}>

It will be avaialble as a prop to the App component: 它将作为App组件的支柱:

class App extends React.Component {
  componentWillMount () {
    this.props.params.screen
  }
}

More about route params at react-router/injected-props 更多关于react-router / inject-props的路由参数

If you're having trouble with re-rendering you can use the component lifecycle method shouldComponentUpdate . 如果您在重新渲染时遇到问题,可以使用组件生命周期方法shouldComponentUpdate Returning false in this method will prevent the component from re-rendering and you'll have the new props (which also include the route params). 在此方法中返回false将阻止组件重新呈现,并且您将拥有新的道具(其中还包括路径参数)。

class App extends React.Component {
  shouldComponentUpdate (nextProps) {
    nextProps.params.screen
    return false
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM