reactjs - 在反应中包含另一个动态列表的动态列表
问题描述
这似乎是一个愚蠢的问题,但它已经困扰了我一段时间了。
假设我的渲染函数显示如下列表:
render(){
return (
<div>
<button onClick={()=>{this.setState({dummyList2:[...this.state.dummyList2,<h2>world</h2>]})}}> add to dummy list 2 </button>
{this.state.dummyList1.map(el=>el)}
</div>
)
我在构造函数中的状态如下:
state={
dummyList2:[]
dummyList1:[<h1>{this.state.dummyList2.map(el=>el)}</h1>]
}
我期望的行为是单击按钮会将项目添加到dummyList2
,并且由于我正在渲染dummyList1
包含第二个列表,它应该显示更新的元素但是这不起作用,我不知道为什么
提前致谢!
编辑
为了更好地了解我想要实现的目标,我创建了一个沙箱
解决方案
我检查了你的代码。通过在构造函数上执行此操作:
this.state = {
...this.state,
dummyList1: [
<div>
<h1>hello</h1>
{this.state.dummyList2.map((el) => el)}
</div>
]
};
You are creating a copy of the dummyList2 and It's not going to be re-render because it's resolved on the constructor, so is not going to be updated. What's happening is that after the component constructor is executed the dummyList1
is
dummyList1: [
<div>
<h1>hello</h1>
<h2>world</h2>
</div>
]
without any reference to dummyList2
If you are trying to render the dummyList2
components inside the HTML that you put inside dummyList1
I'll suggest passing the dummyList2
as a child as I did in this example
Hope it helps. Anything else that I can help you with let me know.
推荐阅读
- python - 全息图散点图的回归线?
- android - 发布模式下无法生成apk
- c# - 在 Unity 中使用 Kinect 身体关节位置仅允许 x 位置随时间变化
- xamarin - 使用 Syncfusion.SfChart 将滑动添加到下一个手势
- java - 有没有办法在不使用包资源管理器/项目/导航器的情况下比较两个打开的文件?
- web-services - 在 docker 容器中访问 WSDL
- javascript - 是 priv.su/src.js 病毒还是什么?
- c# - 谓词条件在 IQueryable 中不起作用但在将 IQueryable 转换为 ToList() 后起作用
- ibm-cloud - 是否可以将对象从一个云对象存储实例复制到另一个。桶在不同的区域
- angular - Angular 7 导航到 parent/:idChildroute/childroute,根据来自服务的路由调用数据