【发布时间】:2018-06-29 17:51:04
【问题描述】:
我只使用了两天的 React,我一直坚持显示获取 JSON 文件的结果。当我执行console.log 时,数据出现在控制台中,但我终生无法弄清楚如何通过渲染功能将其显示回来。
另外,我不知道如何传递或设置变量的值。在这种情况下,我收到警告 - “数据被分配了一个值但从未使用过”
我试过 { JSON.stringify(this.Songs, null, 2) }。 我尝试调用 this.data[0].title 来仅显示 JSON 中的第一个标题,但我收到一个错误,即 0 未定义。
就像 this.data 或 this.Songs 的值在其原始功能之外丢失了。
我尝试过使用 let data、const data、this.data = this.data.bind 等...
如何使这些值可用于 render()? 以及如何将它们呈现到页面?
这是代码,提前致谢:
import React from 'react';
class Songs extends React.Component {
constructor(){
super();
const data = [];
}
componentDidMount() {
fetch('http://localhost:3000/data.json')
.then((response) => response.json())
.then((responseJson) => {
this.Songs = responseJson;
this.data = responseJson;
this.getData(this.Songs);
this.createColumns();
})
.catch((error) => {
console.error(error);
});
}
createColumns() {
this._columns = ['id', 'title', 'original_band', 'description', 'date_posted', 'download_midi_tabs', 'youtube_link', 'download_guitar_m4v' ];
console.log('inside createColumns: ' + this._columns);
}
getData(data){
console.log('inside getData');
console.log(data);
}
render() {
return (
<div>
{ JSON.stringify(this.data, null, 2) }
</div>
);
}
}
export default Songs;
这是来自 JSON 的两行示例:
[ { "id": "1", "title": "2 minutes 2 midnight", "original_band": "Iron Maiden", "description": "", "date_posted": "2012-02-06 17:14:56", "download_midi_tabs": "http://kronusproductions.com/songs_angular/assets/downloads/2_minutes_to_midnight.zip", "youtube_link": "http://youtu.be/VAm3-vyfJwI", "download_guitar_m4v": "http://kronusproductions.com/uploads/serious/2-minutes-to-midnight-vst.mp3", "download_enabled": "1" }, { "id": "2", "title": "909", "original_band": "The Beatles", "description": "Even though this song would be recorded at the end of the Beatles time together, it was one of the first songs that Lennon and McCartney wrote together. I have added horns in the place of the guitar licks that Lennon recorded.", "date_posted": "2012-02-06 17:14:56", "download_midi_tabs": "http://kronusproductions.com/songs_angular/assets/downloads/909.zip", "youtube_link": "https://youtu.be/DxuEYgbUtqE", "download_guitar_m4v": "http://kronusproductions.com/uploads/serious/909-vst.mp3", "download_enabled": "1" }
【问题讨论】:
标签: javascript reactjs