gpt4 book ai didi

javascript - 如何从两个现有对象正确创建一个对象

转载 作者:行者123 更新时间:2023-11-30 19:37:39 25 4
gpt4 key购买 nike

我收集了两个不同的对象形成一个 api,我想在将它们传递给子组件之前将它们组合成一个。

我试图循环其中一个以将第三个创建到 ComponentDidUpdate(可能不是正确的方法),这会弹出一个错误:“超出最大更新深度。当组件在 componentWillUpdate 中重复调用 setState 或componentDidUpdate.React 限制嵌套更新的数量以防止无限循环。”

export default class Router extends Component {

state = {
posts : [],
secciones : [],
postSeccion : [],
}

componentWillMount() {
this.obtenerPublicaciones(); //calling api
this.obtenerSecciones(); //calling api
}

componentDidUpdate(prevProps, prevState) {

this.createPostSeccionArray();


}

createPostSeccionArray() {
const posts = [...this.state.posts];
const secciones = [...this.state.secciones];

//check if the two objects were fetched (sometimes didn't finish fetching one of them)
if(posts.length !== 0 && secciones.length !== 0 ) {

let postSeccionArray = [];

posts.forEach(element => {

const postSeccionElement = {};
const actualPost = element;
const actualSeccion = secciones.find(el => el.id == actualPost.id);
postSeccionElement.post = actualPost;
postSeccionElement.seccion = actualSeccion;
postSeccionArray = [...postSeccionArray, postSeccionElement];
});

this.setState({
postSeccion: postSeccionArray,
})
}

}
}

这是我期望的对象输出数组:

[{
"post": {
"id": 1,
"titulo": "Publicación 1",
"cuerpo": "<p>test <b>asdasd</b></p>",
"seccion": 1,
"fecha_creacion": "2019-04-16T15:16:36.181618Z",
"fecha_edicion": "2019-04-16T15:16:36.181651Z",
"autor": 1
},
"seccion": {
"id": 1,
"nombre": "Deportes",
"descripcion": "test"
}
}]

最佳答案

根据您现在所拥有的,以下内容将修复它。

  componentDidUpdate(prevProps, prevState) {
if(!prevState.postSeccion.length > 0){
this.createPostSeccionArray();
}
}

但是,我会等待您的进一步澄清,之后我将编辑此答案。

关于javascript - 如何从两个现有对象正确创建一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55764208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com