首页 > 解决方案 > 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)

在此处输入图像描述

标签: javascriptreactjs

解决方案


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)
}));

您可以在附加的代码中发现结果数组不是您所期望的。


推荐阅读