Reactjs 未呈现json数组

Reactjs 未呈现json数组,reactjs,Reactjs,我已根据post请求填写了我的myArray。我想用这些值动态地填充表,但是它不呈现任何内容 class Reports extends React.Component { constructor(props) { super(props); this.state = { id:"", myArray: [], } } componentDidMount(e) { console.log("fet

我已根据post请求填写了我的myArray。我想用这些值动态地填充表,但是它不呈现任何内容

class Reports extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      
      id:"",
      myArray: [],
}
}

componentDidMount(e) {
    console.log("fetching")
    fetch('/getMetaReport', {
      method: 'post',
      headers: {'Content-Type':'application/json', 'Accept': 'application/json'},
      body: JSON.stringify({id: 7}),
    }).then(res => res.json()).catch(error => {
      console.error('Error:', error);
  })
  .then(response => {
      console.log(response);
      this.state.myArray.push(response);
      console.log(this.state.myArray)
      
  }) 
  }

我可以在控制台中打印这些值,但无法用它们填充表格

    
    return (
      <div className={s.root}>
        <h2 className="page-title" style={{color: "black"}}>
          Reports
        </h2>
        
<table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Title</th>
                    <th>Date</th>
                </tr>
                </thead>
                <tbody>
                    {
                        this.state.myArray.map((item) => (
                            <tr key={item.id}>
                                <td>{item.id}</td>
                                <td>{item.title}</td>
                                <td>{item.date}</td>
                                <td/>
                            </tr>
                        ))
                    }
                </tbody>
            </table>
        
      </div>
    )
  }


返回(
报告
身份证件
标题
日期
{
this.state.myArray.map((项)=>(
{item.id}
{item.title}
{item.date}
))
}
)
}

为什么它什么也不呈现,如何用JSON数组中的值动态填充我的表?提前感谢您。

您不会触发重播。试试这个


this.setState({'myArray':[…this.state.myArray,response]})

虽然Cody E提到的是正确的,但如果您想将新项“推送”到现有数组中(而不是替换整个数组),最好的方法是使用prevState参数。否则你可能会发现副作用

this.setState((prevState) => {
  return { myArray: [...prevState.myArray, ...response] }
})

更多信息:

我在ComponentDidMount中添加了此属性,但现在它给出了“警告:列表中的每个子项都应该有一个唯一的“键”属性。”错误它引用的是
return
块中的元素。我有点生疏,但这可能意味着您有多个元素具有相同的
项.id
(来自
),或者它希望每个
都有自己的密钥。尝试类似于
的方法,然后对每个
执行类似的操作,但它不起作用:(但感谢添加此项后,我出现了许多错误,但当我按照Cody E所说的操作时,它不会呈现任何内容:(你能详细说明你的错误吗?我肯定这是正确的写作方式。你也可以创建一个沙盒来共享。我会仔细检查响应对象,因为这可能是这里的问题。另外,对于你的情况场景,你不需要使用前一个状态,试试这个:this.setState({myArray:[…response]})我添加了这个.setState({myArray:[…response]})并给出以下错误:未经处理的拒绝(TypeError):传播不可iterable instanceLooks的无效尝试,如响应不是您所认为的。不能在数组中。