首页 > 解决方案 > 在 Reactjs 的方法调用中迭代数组项和空值检查

问题描述

interface State {
  detailsItem: Array<{
    id: string;
    name: string;
designation: string;
  }>;

interface Props{
id: string;
name: string;
desgination:string
}

方法:

sampleItem = () => {
  this.sampleService
    .sampleMethod(this.props.id, this.props.name, this.props.designation)
    .then((response) => {})
    .catch((error) => {
      console.log(error);
    });
};

我想替换道具,我想从 detailsItem 数组中获取 id、name 和 designation。在下面的方法中,我正在尝试这样做,但出现错误

sampleItemOne = () => {
  this.state.detailsItem.map((item) => {
    { item? ( 
            this.sampleService
            .sampleMethod(item.id, item.name, item.designation)
            .then((response) => {})
            .catch((error) => {
              console.log(error);
            })
        : null;
    }
  });
};

我尝试删除道具并在 sampleItemOne 中调用 id、名称和指定,但出现错误:预期分配或函数调用,而是看到一个表达式谁能帮我解决这个问题,我做错了什么!

标签: javascriptarraysreactjstypescript

解决方案


在下面的代码中,您{}在三元组周围添加了一个额外的。这可能是因为您习惯于在 JSX 中使用它来表示表达式,但在像这样的函数体中,它的对象表示法。

this.state.detailsItem.map((item) => {
  {item ? ( 
    this.sampleService
    .sampleMethod(item.id, item.name, item.designation)
    .then((response) => {})
    .catch((error) => {
      console.log(error);
    })
  : null;
  }
});

这是破坏性的,因为上面的代码不是一个有效的对象。

相反,只需使用常规if(无论如何它更具可读性)

this.state.detailsItem.map((item) => {
  if(item) { 
    this.sampleService
    .sampleMethod(item.id, item.name, item.designation)
    .then((response) => {})
    .catch((error) => {
      console.log(error);
    });
  }
});

推荐阅读