为什么我不能在React中返回对象

时间:2019-02-14 10:16:56

标签: javascript reactjs

为什么这总是在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函数中永远不会获得返回值。

3 个答案:

答案 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;
}