首页 > 解决方案 > if else 语句返回 undefined 并带有 redux 状态

问题描述

我有一个函数可以接收一个名为会话的对象。这个对话对象有一个唯一的参与者 ID,我用它来从我的 redux 状态中获取匹配的参与者。一切都很好,但是当我去设置我的联系人时,如果 conversation.conversationSid 为真,它返回未定义。我在这里错过了什么吗?我声明我的变量不正确吗?

const getContact =(conversation) => { 
    console.log(conversation) correctly logs the object 
    let contact = { };
    
   if (conversation?.conversationSid) { // if newSid isnt our defualt
    const psidMatch =  participants.find(({ sid }) =>  sid === conversation?.participantSid ); 
    
    const updatedNumber =  psidMatch?.number?.replace("+", " ")
    contact = contacts.find(({phone_number}) => phone_number === updatedNumber)
   } else {
  contact = { firstName: "kevin", lastName: "baker" }
  
  } 
    
    console.log(contact) // this is returning undefined if the if statement is true.. if false it logs fine. the main contacts array logs fine...
    return contact;
  };

联系人数组

0: {group: Array(1), _id: '6173cae28a', phone_number: '17705555555', firstName: 'Chad', 
1: {group: Array(1), _id: '617b04b75b', phone_number: '18165055555',  firstName: 'Barskin', 
2: {group: Array(1), _id: '617b04d15b', phone_number: '13039555555', firstName: 'Broski',

如果您 console.log 直接在替换下更新数字

 13039555555

标签: javascriptnode.jsreactjs

解决方案


推荐阅读