【问题标题】:React: how to keep sidepanel state between url changes with history.push()?React:如何使用 history.push() 在 url 更改之间保持侧面板状态?
【发布时间】:2017-06-01 17:08:32
【问题描述】:

我有一个固定的侧面板,其中包含一个带有过滤按钮的搜索栏,类似于https://facebook.github.io/react/docs/thinking-in-react.html

列表项是可点击的,并为嵌套路径 url 触发 history.push()

嵌套路径结构是

/category-1
/category-1/product-1
/category-1/product-2
/category-2
/category-2/product-1
/category-2/product-2
 .
 .
 .
/category-n/product-m
/category-n/product-k

用户可以滚动侧面板的列表并选择过滤器。但是,单击列表项(onClick() 后跟 history.push())会导致整个页面(包括侧面板)呈现。这反过来又不会保持侧面板的状态,因此会重置过滤器和滚动位置。

render: function() 看起来像:

return(
  <div id="main-view">
    <Sidepanel history={this.props.history} properties={this.props.properties} />
    React.cloneElement(this.props.children, {this.props});
  </div>
);

React.cloneElement() 是仅应呈现的产品信息容器。

我正在使用react-router, react-redux and redux-simple-router

我是否需要将侧面板的列表滚动位置和过滤值存储在侧面板之外?或者有没有更好的方法在 url 更改之间保持侧面板的状态?

【问题讨论】:

    标签: reactjs react-router react-redux browser-history


    【解决方案1】:

    您的架构与您想要做的不一致。

    只需在您的顶级父组件中呈现导航,它就永远不会丢失状态 - 例如在您的 Application 组件中。那么SidePanel就不会受到路由变化的影响。

    如果需要,您还可以传递回调以设置/更改子级导航(例如 hide()addMenuItems())。

    【讨论】:

    • 谢谢@leo - 这解决了这个问题。我将侧面板移动到Application 的顶层,现在它的状态保持不变,同时 url 得到更新。完美!
    • 很好,很高兴为您提供帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    相关资源
    最近更新 更多