首页 > 解决方案 > 在反应中包含另一个动态列表的动态列表

问题描述

这似乎是一个愚蠢的问题,但它已经困扰了我一段时间了。

假设我的渲染函数显示如下列表:

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包含第二个列表,它应该显示更新的元素但是这不起作用,我不知道为什么

提前致谢!

编辑

为了更好地了解我想要实现的目标,我创建了一个沙箱

标签: reactjs

解决方案


我检查了你的代码。通过在构造函数上执行此操作:

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.


推荐阅读