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

标签 javascript reactjs object state

我收集了两个不同的对象形成一个 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/

相关文章:

javascript - 检查 `created_by` 属性后无法删除播放器对象

javascript - Material UI 自动完成实现,带有包含对象数组(ID 和标签)的选项

php - 如何在 PHP Heredoc 语法中显示数组元素或对象属性的值

c++ - 如何将一个对象的多个实例发送到一个函数中

javascript - 有什么方法可以在没有 JavaScript 的情况下拉伸(stretch) div 吗?

javascript - Angular 2 ChangeDetectionStrategy.OnPush 在输入不改变时触发 ngAfterViewChecked

javascript - 关于 ReactJS 中的 LifeCycles/代码片段中的问题

javascript - 动态更新对象中的 Getter 函数

javascript - Firefox 30.0 中的 ExtJS 3.4 错误

reactjs - 如何使用facebook jest测试.jsx文件,找不到模块