javascript - 使用渲染时卸载 React-router v4

标签 javascript reactjs react-router

可能有点混淆了 render 方法在 react-router 中的工作原理以及“挂载”在 React 中的真正含义。我阅读了文档,它说:

When you use component (instead of render or children, below) the router uses React.createElement to create a new React element from the given component. That means if you provide an inline function to the component attribute, you would create a new component every render. This results in the existing component unmounting and the new component mounting instead of just updating the existing component. When using an inline function for inline rendering, use the render or the children prop (below).

render: func This allows for convenient inline rendering and wrapping without the undesired remounting explained above.

所以我预计当 url 更改时,现有组件不会被卸载,而是保留在那里,从而保存其状态。但这不是我观察到的。这是我的代码:

<div style={styles.content}>
    <Route path={`${this.props.match.url}/summary`} render={() => <ETFViewer/>} />
    <Route path={`${this.props.match.url}/proxy`} render={() => <Proxy/>} />
</div>

因此组件 ETFViewerProxy 渲染得很好,并且它们没有任何问题,但我注意到当我从 /proxy 移动时到 /summary 并返回状态已丢失!而且,我在Chrome中的React devtools中可以看到该组件确实消失了......

enter image description here

那么这是怎么回事呢?有什么方法可以让组件保存其状态并只是“隐藏”吗?

感谢您的帮助!

最佳答案

这个问题有点老了,但在我最近的搜索中出现了。我认为问题在于您没有将 props 与组件一起传递。这是一个例子:

<div style={styles.content}>
<Route path={`${this.props.match.url}/summary`} render={props => <ETFViewer {...props} />} />
<Route path={`${this.props.match.url}/proxy`} render={props => <Proxy {...props} />} />                      
</div>

关于javascript - 使用渲染时卸载 React-router v4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44574583/

相关文章:

javascript - IE 性能问题 - 慢

javascript - 使用数组中的值填充复选框

reactjs - React Router - 渲染组件的问题。白屏

reactjs - React-router 4.0、react-router-dom 和 React-router-redux 之间有什么区别?

url - 如何在react-router中设置和处理语言?

javascript - 使表格中的所有单元格具有相同的宽度等于最宽的单元格宽度

javascript - 本地 D3 无法在线工作

javascript - React 中的 throttle

javascript - 是否有可能在 React 中实现类似 HOC 的类 - 没有类?

reactjs - 如何获取material-ui中checkbox标签的值?