【问题标题】:React cannot display json - data is assigned a value but never usedReact 无法显示 json - 数据被分配了一个值但从未使用过
【发布时间】: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


    【解决方案1】:

    你必须使用setState来设置你的组件状态,这个状态会驻留在组件的state中。

    示例

    class Songs extends React.Component {
      state = {
        data: []
      };
    
      componentDidMount() {
        fetch("http://localhost:3000/data.json")
          .then(response => response.json())
          .then(responseJson => {
            this.setState({ data: responseJson });
          })
          .catch(error => {
            console.error(error);
          });
      }
    
      render() {
        return (
          <div>
            {this.state.data.map(obj => {
              return (
                <div>
                  <h2>{obj.title}</h2>
                  <h3>{obj.original_band}</h3>
                  <p>{obj.description}</p>
                </div>
              );
            })}
          </div>
        );
      }
    }
    

    【讨论】:

    • 首先,感谢@Tholle 向我展示了如何保留变量的值。其次,既然我可以在浏览器中看到 JSON,我该如何“渲染”一个列表,比如数据网格
    • @kronus 不客气!如果不查看您的数据的外观,这很难说。你认为你可以在你的问题中加入一些预览吗?
    • 我刚刚从 JSON 中添加了两行示例,再次感谢您
    • @kronus 没问题。我刚刚用渲染示例更新了答案。
    • 真的很棒。谢谢楼主
    【解决方案2】:

    您的代码有很多问题,但我认为最大的问题是您从未调用过setState。更新 stateprops 是 React 知道触发渲染的方式。

    【讨论】:

      猜你喜欢
      • 2021-04-13
      • 2021-12-04
      • 1970-01-01
      • 2019-05-08
      • 2020-05-04
      • 2017-05-27
      • 2019-04-07
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多