2017-03-28 30 views
0

场景中其他2个字段的值计算字段值:终极版型 - 使用利用的onChange

想一想3个字段:quantitysinglePricetotalPrice。 我需要所有他们在我的表单字段但totalPrice必须重新计算每次我换量或singlePrice通过简单的操作时,你可以想像..

我做了什么:

  • 创建了由数量字段的onChange事件触发的函数,并为singlePrice字段创建了另一个函数。

  • 上面的函数调用与这样的有效载荷的终极版动作:

    { name: name_of_the_updated_field, value: new_field_value }

  • 的行动是由formReducer plugin,使计算和返回更新后的值对象回升。

问题: 我的终极版存储不更新也不是我形式。

我的表单还原器(我必须更新的属性是在另一个属性中)。

import { reducer as formReducer } from 'redux-form'; 

export default formReducer.plugin({ 
    formName: (state, action) => { 
    switch (action.type) { 
     case 'CALC_TOTAL_PRICE': 
     return { 
      ...state, 
      values: { 
      ...state.values, 
      competences: state.values.competences.map((c, i) => { 
       if (i === action.payload.index) { 
       const { name, value } = action.payload; 
       const next = Object.assign({}, c); 
       next[name] = value; 
       next.totalPrice = next.quantity * next.singlePrice 
       return next; 
       } 
       return c; 
      }), 
      }, 
     }; 
     default: 
     return state; 
    } 
    }, 
}); 

我错过了什么吗?如何解决这个问题? 是否有更简单的方法来获得此结果?

任何帮助非常感谢!

回答

0

你可能会认为使用formValueSelector得到了本输入值和计算总的东西喜欢 -

import React, { PropTypes } from 'react'; 
import { Field, reduxForm, formValueSelector, FieldArray, SubmissionError } from 'redux-form'; 
import { connect } from 'react-redux'; 

class NewSaleForm extends React.Component { 

    componentWillReceiveProps(nextProps) { 
     if (nextProps.items && nextProps.items.length > 0) { 
     nextProps.items.forEach((item) => { 
      if (item.price && item.unit) { 
       if (item.unit_discount) { 
        item.total = (item.price - item.unit_discount) * item.unit; 
       } else { 
        item.total = item.price * item.unit; 
       } 
      } else { 
       item.total = ''; 
      } 
     }); 
     } 
    } 

render() { 
    ...... 
} 


NewSaleForm = reduxForm({ // eslint-disable-line 
    form: 'newSaleForm' 
})(NewSaleForm); 

const selector = formValueSelector('newSaleForm'); 

NewSaleForm = connect(state => { // eslint-disable-line 
    const items = selector(state, 'items'); 
    return { 
     items, 
    }; 
})(NewSaleForm); 

export default NewSaleForm; 
+0

扎勒RASEL,感谢您的答复!我理解你的意思,但是我的解释可能并不清楚:我应该以某种方式将数据注入到FieldArray的'fields'属性中,因为我已经有数据适合表单域,一个选择。 这是一个'工作'esample ..我可以请你建议我如何解决它? https://www.webpackbin.com/bins/-Kecgj77Gbxo_4am3WS1 当您从select中选择一个产品时,它应该将数据提供给字段,就像FIeldsArray示例 – Sunrising