【问题标题】:Displaying JSON data using Fetch API and map() in Javascript/Reactjs在 Javascript/Reactjs 中使用 Fetch API 和 map() 显示 JSON 数据
【发布时间】:2023-04-09 15:04:01
【问题描述】:

我一直在尝试从 API 中获取 json 数据并使用 map() 函数显示它。不幸的是,API 以以下格式返回数据:{ "type": ..., "value": ... }。第二个对象 value 包含一个包含我要访问的数据的数组。

有没有一种方法可以访问(或单独列出)API 中的第二个对象?然后我可以在上面运行 map() 。请参阅下面的代码。这当前返回错误:this.state.jokes.map is not a function

附:该代码在包装在数组中的 API 上完美运行,例如http://jsonplaceholder.typicode.com/posts

class JokeList extends React.Component {

    constructor() {
        super();
        this.state = {jokes:[]};

    }

    componentDidMount() {
        fetch(`http://api.icndb.com/jokes`)
            .then(result => result.json())
            .then(jokes => this.setState({jokes}))
    }

    render () {

        return (
            <div> 
                {this.state.jokes.map(joke => 
                       <div key={joke.id}> {joke.joke} </div>)}
            </div>
        );
    }
}

【问题讨论】:

    标签: javascript json rest reactjs


    【解决方案1】:

    尝试使用

    fetch(`http://api.icndb.com/jokes`)
        .then(result => result.json())
        .then(jokes => this.setState({jokes: jokes.value}))
    

    改为。

    这是因为 API 的响应是这样的:

    {
      "type": "...",
      "value": [the value you want],
    }
    

    您需要 value 键的值,因为那是您以后要使用的。

    【讨论】:

      【解决方案2】:
      class JokeList extends React.Component {
      
          constructor() {
              super();
              this.state = {jokes:[]};
      
          }
      
          componentDidMount() {
              fetch(`http://api.icndb.com/jokes`)
                  .then(result => result.json())
                  .then(jokes => this.setState({jokes}))
          }
      
          render () {
      
              return (
                  <div> 
                      {this.state.jokes.map(joke => 
                             <div key={joke.id}> {joke.joke} </div>)}
                  </div>
              );
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-19
        • 1970-01-01
        • 2020-03-29
        • 1970-01-01
        • 2019-01-22
        • 1970-01-01
        • 2018-07-28
        • 1970-01-01
        相关资源
        最近更新 更多