我正在使用 React 和 Redux。我在 FieldArray 中有 FieldArray,我想将子对象添加到内部数组中。我已经完成了代码更改,我可以看到对象已添加到内部数组但页面没有重新呈现,更改没有反映在页面上。
代码更改如下:
主页:渲染功能
<div>
<FieldArray name="parentList" component={CustomCom}
props={this.props}/>
<br/>
<button type="button" className="btn btn-primary"
onClick={event => this.addDoc(mainDTO)}>Add Doc
</button>
</div>
function mapStateToProps(state) {
return {
parentList: state.reqReducer.parentList,
}
}
CustomCom 组件渲染方法
{fields.map((doc, index) => (
<div className="col-sm-12">
{doc.childList && doc.childList != undefined && doc.childList .map((childEle, index) => (
<div>
<div className="row">
//redux field
</div>
<div className="col-sm-4">
<button type="button" className="btn btn-primary"
onClick={event => this.addChild(index,
docs,fields.get(index).childList)}>Add Child
</button>
</div>
</div>
))}
addChild(index, docs, childList){
this.props.addChild(index, docs, childList);
}
function mapStateToProps(state, ownProps) {
return {
docs: state.reqReducer.docs, //same as parentList
childList: state.reqReducer.childList
}
}
//Action
export function addChild(index, docs, childList) {
let newChild= {};
newChild.prop1 = null
newChild.prop2 = null
childList.push(newChild)
docs[index].childList = childList;
return (dispatch) => {
dispatch(setDoc(docs));
}
}
export function setDoc(payload) {
return {
type: ADD_DOC,
payload: payload
}
}
//Reducer
case ADD_DOC:
return {...state, parentList: action.payload};
在调用 addChild 时,我在父列表中设置子项后调度操作 ADD_DOC,然后它将使用新添加的子项设置/更新 parentList。我在父 FieldArray 的主页中使用 parentList。请让我知道为什么它没有被渲染,任何指导都会非常有帮助。
谢谢你。
更新-> 请让我知道我是否可以在主数组循环中访问这样的子数组(doc.childList),其中 doc 是父元素
{fields.map((doc, index) => ( //Main array traversing
<div>
<div className="col-sm-12">
{doc.childList && doc.childList != undefined && doc.childList.map((singleChild, index) => (
))}
</div>
</div>
}
更新2:
组件已渲染,但 doc.childList 未定义。试图更改代码
-> 首先尝试我必须更改遍历子数组的代码: doc.childList 更改为 fields.get(index).childList ;现在我能够看到 childList 但代码 fields.get(index).childList.map 不起作用。
-> 第二次尝试移动子数组遍历到单独的组件,它起作用了。发布完整代码作为答案。
谢谢你。