从返回 NAN 而不是数字的选择器中添加值

Adding values from Selectors returning NAN instead of number

我总共得到一个 NAN return。我试图让它在下面的代码段中添加所有可用的选择器。查看总行...

Form = connect(state => {
  const equipmentTotal = selector(state, 'equipment.total'); 
  const softwareTotal = selector(state, 'softwares.total');
  const thirdPartyEquipmentTotal = selector(state, 'thirdPartys.totalFees');
  const miscTotal = selector(state, 'miscTotal');
  const tradeInTotal = selector(state, 'orderHeader.tradein');

  return { //Returning data like the following is the equivalent of using ({ }) which is an object-literal as an expression in ES6... docs for more info.
    total: equipmentTotal + softwareTotal + thirdPartyEquipmentTotal + miscTotal + tradeInTotal,
  };
  },
)(Form);

但是,如果其中一个选择器未定义(空),则它 returns NAN。如果状态中没有定义数字,有没有办法将选择器设置为 return 零?理想情况下,我不想在表单字段中设置默认值 0,因为这会要求用户突出显示并删除它,或者可能不小心在输入的数字末尾添加 0。所以用户在选择字段后输入 29 不小心得到 290。

最简单的方法是使用 ||(or) JavaScript 运算符。它 return 是第一个真值。因此,如果从您的选择器中 returned 的值是 undefindednull,甚至 0,它将 return 0;

Form = connect(state => {
    const equipmentTotal = selector(state, 'equipment.total') || 0;
    const softwareTotal = selector(state, 'softwares.total') || 0;
    const thirdPartyEquipmentTotal = selector(state, 'thirdPartys.totalFees') || 0;
    const miscTotal = selector(state, 'miscTotal') || 0;
    const tradeInTotal = selector(state, 'orderHeader.tradein') || 0;

    return { //Returning data like the following is the equivalent of using ({ }) which is an object-literal as an expression in ES6... docs for more info.
        total: equipmentTotal + softwareTotal + thirdPartyEquipmentTotal + miscTotal + tradeInTotal,
    };
},
)(Form);