React正在渲染[object object]而不是JSX [英] React is rendering [object object] rather than the JSX

查看:818
本文介绍了React正在渲染[object object]而不是JSX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用对象(而不是数组)呈现网站上的日记条目,但遇到了问题,这是我当前的代码

I'm trying to render out journal entries on my site with an object (not array) and I am running into an issue, here is my current code

  populateJournal(){
const j = Object.values(this.state.journal);
var journalEntries = '';

  for (var i = 0; i < j.length; i++){
    journalEntries+=
      <div>
      <h3>{j[i].title} - {j[i].date}</h3>
      <p>{j[i].entry}</p>
      </div>;

  }

 return(<div>{journalEntries}</div>);

}

当我调用此函数时,它将呈现"<div>[object object]</div>",并且div之间的文本为纯文本.

When i call this function it renders "<div>[object object]</div>" and the text between the divs is plain text.

当我将循环更改为"journalEntries = <div...."时,它将按预期方式渲染出最后一个日记帐分录,但问题是它实际上并未在循环后附加日记帐分录.

When i change the loop to say "journalEntries = <div...." it renders out the last journal entry as expected, but the issue is that it's not actually appending the journal entries with the loop.

想法?

推荐答案

将定义为journalEntries的字符串替换为一个字符串,将其定义为数组并将JSX元素推入该数组以进行渲染

Inspead of a defining journalEntries as a string define it as an array and push the JSX elements to the array in order to render like

populateJournal(){

    const j = Object.values(this.state.journal);
    var journalEntries = [];

      for (var i = 0; i < j.length; i++){
        journalEntries.push(
          <div>
          <h3>{j[i].title} - {j[i].date}</h3>
          <p>{j[i].entry}</p>
          </div>);

      }

     return(<div>{journalEntries}</div>);

}

当您附加到字符串时,您实际上不是在附加字符串,而是一个不正确的对象,因此您会得到[Object Object]

When you append to the String, you are not actually appending a string but an object which is incorrect and hence you get [Object Object]

您还可以使用map渲染上下文.有关如何使用地图的信息,请参见以下答案:

You can also use map to render your context. See this answer on how to use map:

REACT JS:数据显示和数组操作

这篇关于React正在渲染[object object]而不是JSX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆