javascript - map() 不返回任何内容
问题描述
在 onClick 按钮中,我有一个函数可以发出 GET 请愿并接收 json 数组。当我尝试向用户显示它时,没有任何变化,尽管如果我将 console.log 放在地图中,我会显示并遍历所有对象。
fetch('http://localhost:3000/GetApunte',{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
})
.then(response=>response.json())
.then(responseJson => {
this.datosCargados=true;
this.anotaciones=responseJson;
//cuerpo()
return(
<tbody>
{this.anotaciones.map((anotacion, index)=>{
const {titulo, body} = anotacion
return(
<tr key={index}>
<td>{titulo}</td>
<td>{body}</td>
</tr>
)
})}
</tbody>
);
});
我的班级结构是这样的:
export default class Apuntes extends React.Component{
state ={}
getApuntes(){}
render(){
return(
<button onClick={()=> this.getApuntes()}>Mostrar Apuntes</button>
)
}
}
annotaciones 在州内,这就是我使用 this.anotaciones 的原因
解决方案
而不是在承诺中返回 JSX,只需将 annotaciones 保存到状态中。您可以将表的生成提取到单独的函数中,例如
const generarAnotaciones = () =>
<tbody>
{this.anotaciones.map((anotacion, index) => {
const { titulo, body } = anotacion
return (
<tr key={index}>
<td>{titulo}</td>
<td>{body}</td>
</tr>
)
})}
</tbody>
那么你的班级应该是这样的:
export default class Apuntes extends React.Component {
state = {}
getApuntes() { }
render() {
return (
<>
<button onClick={() => this.getApuntes()}>Mostrar Apuntes</button>
{generarAnotaciones()}
</>
)
}
}
推荐阅读
- css - 在 CSS 中实现弹出窗口的布局问题
- css - 多行时css为空
- c# - 下拉组合框时停止更改文本
- c++ - C++ 等价于 Java Map getOrDefault?
- javascript - 需要帮助在二维数组上构建带有 JSX 标记的双循环
- javascript - 为什么没有使用 react-hook-form 在 Material UI Autocomplete 中设置初始值?
- jquery - ckeditor 无法发送值
- python - 动态修改yaml并保留所有格式和注释-python
- python - 如何在不发生冲突的情况下捕获 psycopg2.DataError 和 psycopg2.errors.BadCopyFileFormat
- c++ - 如何将 C++11 标志传递给“npm install”?