如何使用 react-router 触发状态更改? [英] How can I use react-router to trigger state changes?

查看:49
本文介绍了如何使用 react-router 触发状态更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在掌握 React 和 react-router,但我想知道如何使用 react-router 来简单地更新应用程序状态,而无需重新渲染 DOM 节点.

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.

例如,假设我有:

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

我想重用 react-router 的匹配,但只是更新 App 组件的当前屏幕.

I'd like to re-use react-router's matching but simply update the App component's current screen.

原因是假设在上面的例子中我有三个水平排列的屏幕,一次只有一个可见.当路线改变时,我想在适当的屏幕中设置动画.如果我通过为每个路由分配一个组件来实现这一点,那么在路由匹配之前,react-router 不会渲染其他屏幕,并且屏幕滑入会有明显的延迟.

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.

但是,如果我将所有三个屏幕都保留在 DOM 中并简单地切换状态以触发 CSS 转换,则不会有延迟(因为适当使用 will-change,浏览器可以预渲染离屏层).

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).

我已经尝试了六种方法来实现这一点,但它们都非常笨拙,或者涉及稍微复制匹配代码.我做错了什么?

I've tried half a dozen ways of achieving this but they're all very hacky or involve duplicating the matching code somewhat. What am I doing wrong?

另外,如果可能的话,我想避免添加像 Redux 这样的东西来解决这个问题.

Also, I'd like to avoid adding something like Redux just to fix this if possible.

推荐答案

所以你想要类似于 奇观?

在您的情况下,我会将所有屏幕作为 App 组件的子项,并使用 react-router 的参数来了解您在哪个屏幕上.

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 组件的道具:

It will be avaialble as a prop to the App component:

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

react-router 上了解更多关于路由参数的信息/injected-props

如果您在重新渲染时遇到问题,可以使用组件生命周期方法 shouldComponentUpdate.在此方法中返回 false 将阻止组件重新渲染,您将拥有新的道具(其中还包括路由参数).

If you're having trouble with re-rendering you can use the component lifecycle method 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).

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

这篇关于如何使用 react-router 触发状态更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆