我有一个组件,Split,它有两个孩子。第一个孩子将显示在屏幕的左边,第二个孩子显示在右边。如果屏幕宽度低于某个点,则只显示右侧,左侧将从DOM中移除。
示例子组件可以是Sidebar组件和Content组件。对于移动设备,我不想显示菜单,但有一个特殊的移动菜单,我弹出。
我的问题是:在不卸载和重新挂载Content组件的情况下,如何删除Content组件?
我的Content组件在componentDidMount上获取数据,我不希望它再次重新获取或重新挂载(从而丢弃用户输入)。
基本上,我有这样的东西:
<Split>
<Sidebar/>
<Content/>
</Split>Split的呈现方法如下所示:
let children;
let firstChild = this.props.children[0];
let lastChild = this.props.children.pop();
if (this.state.responsive === 'singleColumn') {
children = (
<div>
<div style={{display: 'none'}}>{firstChild}</div>
{lastChild}
</div>
);
} else {
children = (
<div>
{firstChild}
{lastChild}
</div>
);
}
return (
<div>
{children}
</div>
);即使{lastChild}总是呈现,无论发生什么,每次拆分都必须重新呈现时,它仍然会被卸载和重新装入!
即使有这样的呈现:
return (
<div>
{this.props.children.pop()}
</div>
);使最后一个子项(永不更改)在呈现之前被卸载和重新挂载。
如果我修改Split并将始终位于DOM中的组件作为属性传递,如下所示:
<Split staticComponent={<Content />}>
<Sidebar />
</Split>效果很好。那么,为什么在我弹出最后一个像这个{this.props.children.pop()}这样的孩子而不是这个{this.props.staticComponent}的时候,它不起作用?
有什么办法能解决这个问题吗?
发布于 2016-03-23 20:07:20
终于解决了这个问题!我重写了Split的渲染代码,如下所示:
let left;
if (this.state.responsive !== 'singleColumn') {
left = this.props.children.slice(0, -1);
}
return (
<div ref="split" className={classes.join(' ')}>
{left}
{this.props.children[this.props.children.length-1]}
</div>
);这样,最后一个孩子总是被呈现出来。显然,pop()没有工作,因为我修改了最初的孩子数组,这触发了奇怪的行为。
发布于 2016-03-23 18:59:15
这可以使用生命周期方法: shouldComponentUpdate:
shouldComponentUpdate: function(nextProps, nextState) {
return this.props.value !== nextProps.value;
}如果内部逻辑返回false,则组件将不会更新。
查看文档:https://facebook.github.io/react/docs/advanced-performance.html
发布于 2016-03-23 19:22:45
您可以在组件的生命周期中使用shouldComponentUpdate函数。如果它返回false,则根据文档
如果shouldComponentUpdate返回false,那么呈现()将被完全跳过,直到下一个状态发生变化。此外,不会调用componentWillUpdate和componentDidUpdate。
https://stackoverflow.com/questions/36186454
复制相似问题