我正在使用从Rails api提供数据的React应用程序。我目前正在处理一个包含嵌套关联的表单(即在model_a中有很多model_b'并且你可以用相同的形式创建它们。)
我遇到的问题是Rails希望与某个命名约定嵌套关联,并且控制参数在发送到rails时如何命名的相同字段也控制React在Rails API时如何找到正确的数据响应。
这在编辑页面上会出现问题,因为我想要显示models_a' s(Retailers
)已经存在的model_b' s(在这种情况下为SpendingThresholds
)当我更改'名称'在适合铁路方面的领域,React不知道在哪里寻找这些数据。当我尝试直接传递数据时,它会以不同类型的数组形式出现,某些函数会失败。
我认为这比在这里告诉它更容易显示
最初我有这个
<FieldArray
name="spending_thresholds"
component={renderSpendingThresholds}
/>
和数据一样,
Object {_isFieldArray: true, forEach: function, get: function, getAll: function, insert: function…
来自Rails API的React应用程序,该应用程序正常运行,但名称&#39;不喜欢Rails喜欢(Rails希望它被称为&#39; spend_thresholds_attributes&#39; 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组件
fields
组件中的renderSpendingThresholds
属性是根据我输入的方式而有所不同的对象
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>
);
答案 0 :(得分:1)
看起来你正在通过道具传递字段,然后在fields
的回调中将renderSpendingThresholds
从道具中解构出来并丢弃其余部分。根据文档,特定的redux-form
对象将传递给render
回调。你基本上覆盖了这个。尝试将{field}
更改为member
或spending_threshold
。然后,您可以使用特定的map
函数迭代spending_threshold
项。您的field
道具仍应在member.fields
或类似内容下提供。
答案 1 :(得分:0)
对于您当前显示的代码,谁准确处理提交?
您使用表单提交的原始流程吗?
如果是的话,请自行处理。**这行代码,看起来很奇怪:
onClick={() => fields.remove(index)}
直接与州值互动... 你需要通过
更新状态this.setState({fields: FIELDS_WITHOUT_ITEM})
现在当您需要处理自己的提交时,您并不真正关心输入名称。因为您使用状态作为输入。
即:
class FormSpending extends Component {
handleSubmit() {
var fieldsData = this.state.fields.map(field => {
return {
whateverkey: field.dontcare,
otherKey: field.anotherDontCare
};
});
var formData = {
fields: fieldsData
};
ajaxLibrary.post(URL_HERE, formData).....
}
render() {
return (
...
<form onSubmit={()=>this.handleSubmit()}>
...
</form>
...
);
}
}