可能有点混淆了 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>
因此组件 ETFViewer
和 Proxy
渲染得很好,并且它们没有任何问题,但我注意到当我从 /proxy
移动时到 /summary
并返回状态已丢失!而且,我在Chrome中的React devtools中可以看到该组件确实消失了......
那么这是怎么回事呢?有什么方法可以让组件保存其状态并只是“隐藏”吗?
感谢您的帮助!
最佳答案
这个问题有点老了,但在我最近的搜索中出现了。我认为问题在于您没有将 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/