javascript - 在 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、名称和指定,但出现错误:预期分配或函数调用,而是看到一个表达式谁能帮我解决这个问题,我做错了什么!
解决方案
在下面的代码中,您{}
在三元组周围添加了一个额外的。这可能是因为您习惯于在 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);
});
}
});
推荐阅读
- r - 查找在 R 中构成主键的变量组合
- java - 在没有嵌套循环的列表中查找重复项?
- spring-boot - SpringApplication.run 运行所有 CommandLineRunner bean
- java - Eclipse:Java:OpenCV:“无法解析导入组织。”
- tomcat - 无法让“remote-exec”启动 tomcat
- javascript - 在数组映射中转换某些属性名称的优雅方法
- python - 检查 QSettings 是否使用默认值
- macos - 如何在 Mac OS X 上使用 Python 套接字启用混杂模式
- javascript - 在 Web 组件中包含外部库是不好的做法吗?
- javascript - 基本的javascript概念理解