在React.js中的render return()中显示获取结果 [英] Show fetch results in render return() in React.js

查看:156
本文介绍了在React.js中的render return()中显示获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是关于如何在render return()中显示数组结果.
我提取了API,现在得到的结果存储在数组中.我需要显示此结果,但是我在返回中使用了for {},但它不起作用,并且我还尝试了.map和map is undefined.

My question is about how to show array results in render return().
I made a fetch to the API and now I get results that get stored in a array. I need to show this results but I tried with a for{} inside the return and it doesn't work, and I also tried with .map and the map is undefined.

fetch(url + '/couch-model/?limit=10&offset=0', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
        }
    }).then(res => {
        if (res.ok) {
            return res.json();
        } else {
            throw Error(res.statusText);
        }
    }).then(json => {
        this.setState({
             models: json.results
        }, () => {
            /*console.log('modelosJSON: ', json);*/
        });
    })

render() {
    const { isLoaded } = this.state;
    const modelsArray = this.state.models;

    console.log('modelos: ', modelsArray);

    if (!isLoaded) {
        return (
            <div>Loading...</div>
        )
    } else {

        return (
            <div>
                /*show results here*/
            </div>
        )
   }
}

数组是这样的:

推荐答案

模型数组是从fetch返回的json的results,因此您可以在您的状态下将其设置为models,并将isLoaded设置为true,以便在加载模型时隐藏加载指示器.

The array of models is the results of the json returned from your fetch, so you can set that as models in your state instead, and set isLoaded to true so the loading indicator is hidden when the models are loaded.

示例

class App extends React.Component {
  state = { isLoaded: false, models: [] };

  componentDidMount() {
    fetch(url + "/couch-model/?limit=10&offset=0", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Authorization: "JWT " + JSON.parse(localStorage.getItem("token")).token
      }
    })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw Error(res.statusText);
        }
      })
      .then(json => {
        this.setState({
          models: json.results,
          isLoaded: true
        });
      });
  }

  render() {
    const { isLoaded, models } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    }

    return <div>{models.map(model => <div key={model.id}>{model.code}</div>)}</div>;
  }
}

这篇关于在React.js中的render return()中显示获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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