我正在使用带有 FieldArray 的 redux-form。默认情况下,数组中有 1 个元素,它是从 JSON 填充的。我最多可以在 FieldArray 组件中添加 3 个元素。
在下面的代码中,'elementList' 属性来自 JSON,我也存储了名为 'elements' 和 'elementList' 的变量。我首先使用 JSON 中的 elementList 初始化这些存储变量,然后在单击“添加元素”时不断更新存储变量。我可以看到商店变量正在正确更新,但在屏幕上字段数组元素没有更新。这可能是因为 FieldArray 中的名称属性“elementList”可能引用 JSON 元素。
是否有可能,如果我可以在“FieldArray”的名称属性中引用存储变量“elementList”或“elements”。请指教。
主页
<div>
<FieldArray name="elementList" component={Elements}
props={this.props}/>
<button type="button" className="btn btn-primary"
onClick={event => this.addElement(elementDTO)}>Add Element
</button>
<br/>
</div>
addElement(elementDTO){
if(this.props.elements && this.props.elements!=undefined && this.props.elements.length >= 3){
return;
}
this.props.addReqElement(this.props.elements);
}
字段数组页面
const elements= ({props, meta: {error, submitFailed}}) => {
const {fields} = props;
return (
{fields.map((element, index) => (
<div>
//Field definitions
</div>
))}
谢谢
更新:从 Redux Action 和 Reducer 添加方法
export function addReqElement(childList) {
let state = store.getState()
let newChild=
state.requestReducer.DTOobj.requestDoc; //this is an empty element coming from backend with few properties and adding rest of the //proerties as below to create a new child
newChild.prop1 = null
newChild.prop2 = null
childList.push(newChild)
return (dispatch) => {
dispatch(setDoc(childList));
}
}
export function setDoc(payload) {
return {
type: ADD_DOC,
payload: payload
}
}
更新 2:我尝试删除 push 并使用 spread operator ,但它没有用。我也有内部数组,这在我使用不同的策略时起作用。我拉取父数组,它是索引并用新的内部数组更新父数组。它有效,但父数组我不知道我应该如何使它工作。我尝试将主数组设置为表单props并通过分派动作来呈现整个页面,但它不起作用。lz有什么建议吗?
从主阵列页面:
render() {
const {fields, parentArrayFromStore} = this.props;
return (
<div className="col-sm-12">
{fields.map((doc, index) => (
<div key={index}>
<div className="col-sm-12">
<FieldArray name={`${doc}.innerArrayList`} component={CustomInnerArrayComponent}/>
</div>
<div className="row">
<div className="col-sm-4">
<button type="button" className="btn btn-primary"
onClick={event => this.addInnerArray(index, parentArrayFromStore ,fields.get(index).innerArrayList)}>Add Printer
</button>
</div>
</div>
</div>
))}
</div>)
}
在动作类
export function addInnerArray(index, parentArrayFromStore, innerArrayList) {
let newInnerItem= {};
newInnerItem.prop1 = null
newInnerItem.prop2 = null
innerArrayList.push(newInnerItem)
parentArrayFromStore[index].innerArrayList = innerArrayList;
return (dispatch) => {
dispatch(setParentArray(parentArrayFromStore));
}
}
export function setParentArray(payload) {
return {
type: ADD_DOC,
payload: payload
}
}