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

时间:2018-03-27 18:09:15

标签: reactjs ecmascript-6 redux redux-form

我总共获得了NAN回报。我试图让它在下面的代码中添加所有可用的选择器。见总线...

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);

但如果单个选择器未定义(null),则返回NAN。如果在状态中没有定义数字,有没有办法可以设置Selector返回零?理想情况下,我不想在表单字段中设置默认值0,因为它需要用户突出显示并删除它,或者可能意外地在输入的数字的末尾添加0。因此用户在意外选择了野外建筑290之后输入了29。

1 个答案:

答案 0 :(得分:1)

最简单的方法是使用||(或)JavaScript运算符。它返回第一个真值。因此,如果您的选择器返回的值为undefindednull,甚至0,则会返回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);