javascript - ReactJS 未定义 arr.map
问题描述
我正在从 API 获取数据,然后使用arr.map()过滤数据*(API 返回不必要的属性)
这是有效的:
fetchTable() {
const url = 'http://localhost:8000/issues/assigned/';
const value = this.state.selectedOption;
const string = url+value;
fetch(string)
.then(function(response) {
return response.json();
})
.then((myJson) => this.setState({data: myJson.issues}));
}
const filteredResult1 = this.state.data.map(item => (
{
name: item.fields ? item.fields.assignee.name : '',
id: item.id,
key: item.key,
timespent: item.fields ? this.timeConvert(item.fields.timespent) : '',
project: item.fields ? item.fields.project.name : '',
status: item.fields ? item.fields.status.name : '',
created: item.fields ? item.fields.created : '',
resolution: item.fields ? item.fields.resolutiondate : ''
}
));
但是现在我需要 setState 多次,所以我可以使用过滤后的数据为每个数组渲染一个表,但是 map 的结果总是未定义的!
.then((myJson) => this.setState({data: [...this.state.data, myJson.issues]}));
这不起作用:
fetchTable() {
const url = 'http://localhost:8000/issues/assigned/';
const value = this.state.selectedOption;
const string = url+value;
fetch(string)
.then(function(response) {
return response.json();
})
.then((myJson) => this.setState({data: [...this.state.data, myJson.issues]}));
}
var result = this.state.data.map((item)=>{ return {id:item.id, example: item.example}; });
console.log(result)
解决方案
let array1 = [
1,2,3
];
let array2 = [
4,5,6
]
// ...array1 is destructuring array1
// and which leads to an unexpected result
console.log([...array1, array2]);
更改此行
.then((myJson) => this.setState({data: [...this.state.data, myJson.issues]}));
对此
.then((myJson) => this.setState({
data: this.state.data.concat(myJson.issues)
}));
您可以在附加的代码中发现结果数组不是您所期望的。
推荐阅读
- three.js - three.js 在平面 XZ 上绘制椭圆
- jquery - 我应该如何安装jquery?
- sql-server - 汇总后,如何从审计表中拆分更改类型?
- airflow - 需要创建自定义 s3KeySensor
- c# - Ajax 调用未使用剃须刀页面重定向到所需页面
- excel - 将 spreasheet 与 StringValues 进行比较,Find 方法找到一些值,但没有找到其他值
- excel - 如果匹配键和同一行中的另一个值大于 1,则 Excel 查找
- matlab - 如何将4D矩阵的图形保存在matlab的子文件夹中
- python - ValueError:优化器得到一个空的参数列表(nn.parameter 在父类中不持久)
- html - 如何在 CSS 中使用“object-fit:contain”并且在图像上仍然有边框半径?