【问题标题】:reactjs: Displaying an array data inside <tr> tag [duplicate]reactjs:在<tr>标签内显示数组数据[重复]
【发布时间】:2018-09-12 09:20:08
【问题描述】:

我以这种方式从 api 获得响应 data:Array(3) 0:"new" 1:"ruby" 2:"ruby"

我想在 jsx 表达式内的 tr 元素下显示此数据。我做了一个循环来遍历这样的数组

let course = [];
		let userid = this.props.match.params.userid;
		axios.get("someapi") //the api to hit request
			.then((response) => {
				console.log(response);
				for (var i = 0; i < response.data.length; i++) {
					console.log(response.data[i]);
					course.push(response.data[i]);
				}
				console.log("course", course);
				this.setState({ course: course });
				console.log("state course", this.state.course);
			});

我得到了console.log 中的所有值,带有“course”和“state course”,但无法将它映射到 tbody 中以在 tr 标签中显示它。我想在这个里面渲染它

<tbody>

  <tr>new,ruby and ruby should be displayed here as a list</tr>

</tbody>

我做错了什么?

【问题讨论】:

  • 发布你所有的代码,尤其是你正在渲染的代码
  • 你没有映射this.state.course...

标签: javascript reactjs jsx


【解决方案1】:

在你的桌子里面

<tbody>
{this.state.course.map(ele => 
   <tr>{ele}</tr>
)}
</tbody>

这应该可以。

你也可以参考 React doc 的部分:List and Key.

【讨论】:

  • 说无法读取未定义的属性映射。
  • 确保它在你的构造函数中被初始化为一个数组
  • 是的,它成功了。谢谢。
【解决方案2】:

如果您希望将所有三门课程都放在同一个 &lt;tr&gt; 标记中作为列表,您可以尝试:

let course = [];
let userid = this.props.match.params.userid;
axios.get("someapi") //the api to hit request
    .then((response) => {
        console.log(response);
        course = response.data.join(", ");
        console.log("course", course);
        this.setState({ course: course });
        console.log("state course", this.state.course);
    });

然后在 &lt;tr&gt; 标签内的 jsx 中使用 course 变量。

如果您想为每个课程集打印一个tr courses 等于 response.data 并在您的 jsx 中映射它

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多