3

我正在使用 MobX @observer 和 @withRouter (react-router-v4) 像这样包装页面组件

@withRouter
@inject('stores')
@observer
class Page extends Component {
  render() {
    return (
      <div>
        <NavBar />
        <Header title={this.props.stores.UIStore.title} />
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route exact path="/about" component={AboutPage} />
          <Route component={NotFound} />
        </Switch>
      </div>
    )
  }

问题
当路由位置更改时,NavBar 和 Header 组件总是使用相同的道具重新渲染(没有任何状态更新)。react-perf 在路由更改时显示许多浪费的渲染(没有道具/状态更新)。

NavBar 包括 Link 和一些 MobX 状态(仅使用 @observer+@inject 包装的 NavBar)
Header 只是一个无状态组件。

页面组件需要 @withRouter 导致 @observer (MobX) 中断 react-router ( https://github.com/mobxjs/mobx-react/issues/210 )

如何防止 NavBar 和 Header 因路由位置更改而重新渲染?只有当 mobx 状态更新时才允许重新渲染。

4

1 回答 1

2

我知道这已经很老了,但这就是我在项目中解决同样问题的方法:

  1. 不要同时使用 withRouter 和观察者。如果位置或匹配对象更改,则 shouldComponentUpdate 的观察者实现将返回 true。
  2. 当您只需要历史或位置对象时,请使用 mobx-react-router 中的 routerStore ( https://github.com/alisd23/mobx-react-router )
  3. 当您需要匹配时(通常是因为参数),制作一个使用 withRouter 的非观察者组件并将必要的参数传递给较低级别​​的层次结构。
于 2019-11-27T17:26:23.877 回答