【问题标题】:How to prevent react router from re-rendering a previously rendered page?如何防止反应路由器重新渲染以前渲染的页面?
【发布时间】:2023-03-04 09:17:01
【问题描述】:

我认为我在使用 react 路由器时遇到了一些问题。如何防止 React Router 重新渲染之前渲染的页面?

我有这样的路由器代码:

class App extends React.Component {
  render() {
    return (
        <div>
            <NavBar/>
            {this.props.children}
        </div>
    );
  }
}

ReactDOM.render(
    (
        <Router history={hashHistory}>
            <Route path="/" component={App}>
                <IndexRoute component={Gateway} />
                <Route path="home" component={Gateway} />
                <Route path="categories" component={Categories} />
            </Route>
        </Router>
    ), document.getElementById('my-app')
);

当我第一次访问页面时,它点击索引,网关组件被渲染。然后我点击“categories”链接,Categories 组件就被渲染了。然后,当我再次单击“主页”链接时,组件网关被重新渲染。它的状态得到了RESET。这真的很令人沮丧,因为我无法弄清楚为什么它的状态会被重置。

有什么解决办法吗?

【问题讨论】:

  • 如果你没有使用任何像 Redux 这样的状态管理,那么你必须寻找正确的方法来使用 React 在路由之间共享状态。看看这篇文章中的答案:stackoverflow.com/questions/41108701/… 或谷歌类似“react router share state between routes”

标签: reactjs react-router


【解决方案1】:

如果有任何你想保存的状态,你应该把它存储在某个地方,比如组件的状态(或者如果你使用 redux,则为 redux 状态)。

在 react 中,您可以在组件中定义函数 shouldComponentUpdate() 以强制 React 不重新渲染您的 DOM。但是在 react-router 的情况下,第一个路由的 DOM 被破坏(不仅仅是隐藏),因此应该重新渲染。

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 2021-04-23
    • 2020-04-24
    • 2019-04-25
    • 2018-01-05
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多