ruby-on-rails – React的新功能:为什么一个阵列的处理方式与另
我正在研究一个从Rails api提供数据的React应用程序.我目前正在处理一个包含嵌套关联的表单(即在model_a中有许多model_b,你可以用相同的形式创建它们).
我遇到的问题是Rails期望与某个命名约定嵌套关联,并且控制参数在发送到rails时如何命名的相同字段也控制React在Rails API响应时如何找到正确的数据. 这在编辑页面上会出现问题,因为我想显示models_a(零售商)已经存在的model_b(在这种情况下为SpendingThresholds),当我更改’name’字段以适应rails侧时,React不知道在哪里寻找那个数据了.当我尝试直接传递数据时,它会以不同类型的数组形式出现,某些函数会失败. 我认为这比在这里告诉更容易 最初我有这个 <FieldArray name="spending_thresholds" component={renderSpendingThresholds} /> 和数据一样 Object {_isFieldArray: true,forEach: function,get: function,getAll: function,insert: function… 来自Rails API的我的React应用程序,但是“名称”不适合Rails喜欢(Rails希望它被称为’spend_thresholds_attributes’,以使accepts_nested_attributes工作)所以我将其更改为 <FieldArray name="spending_thresholds_attributes" fields={this.props.retailer.spending_thresholds} component={renderSpendingThresholds} /> 并且数据以此格式开始传递到renderSpendingThresholds组件 [Object] 0:Object length:1 __proto__:Array(0) 由于某些原因,React不喜欢. 任何人都知道如何解决这个问题/为什么那些从Rails端获得相同信息的对象被区别对待? EDITS renderSpendingThresholds组件 renderSpendingThresholds组件中的fields属性是根据我输入方式而不同的对象 const renderSpendingThresholds = ({ fields }) => ( <ul className="spending-thresholds"> <li> <Button size="sm" color="secondary" onClick={(e) => { fields.push({}); e.preventDefault(); } }> Add Spending Threshold </Button> </li> {fields.map((spending_threshold,index) => ( <li key={index}> <h4>Spending Threshold #{index + 1}</h4> <Button size="sm" color="danger" title="Remove Spending Threshold" onClick={() => fields.remove(index)} > Remove </Button> <Field name={`${spending_threshold}.spend_amount`} type="number" component={renderField} label="Spend Amount" placeholder="0" /> <Field name={`${spending_threshold}.bonus_credits`} type="number" component={renderField} label="Bonus Credits" placeholder="0" /> </li> ))} </ul> ); 解决方法
看起来你正在通过道具传递字段,然后在renderSpendingThresholds的回调中将这些字段解析出来,并丢弃其余部分.根据文档,特定的redux-form对象被传递给render回调.你基本上覆盖了这个.尝试将{field}更改为member或spend_threshold.然后,您可以使用特定的map函数迭代spend_threshold项.您的野战道具应该仍然可以在member.fields或类似的东西下使用.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |