为什么这总是在React with Redux中返回未定义?
searchCustomer = id =>{
customers = [...this.props.data];
customers.forEach(customer=>){if(customer.id === id){return customer}};
}
customerDetails = e =>{
const customer = this.searchCustomer(id);
console.log(customer);
}
控制台日志始终未定义。如果您在返回对象之前记录该对象,则该对象将显示正确的对象,但在customerDetail函数中永远不会获得返回值。
答案 0 :(得分:2)
因为您无法返回forEach
更改为
searchCustomer = id => this.props.data.find(customer => customer.id === id)
答案 1 :(得分:1)
您不能像这样从forEach
循环中返回值...尝试使用find
函数,这样会更容易...
searchCustomer = id => {
return this.props.data.find(customer => customer.id === id)
}
customerDetails = e => {
const customer = this.searchCustomer(id);
console.log(customer);
}
答案 2 :(得分:-1)
您没有从searchCustomer
返回任何信息。应该是
searchCustomer = id =>{
customers = [...this.props.data];
customers.forEach(customer=>){if(customer.id === id){return customer}};
return customers;
}