简体   繁体   English

在 React.js 中的 render return() 中显示获取结果

[英]Show fetch results in render return() in React.js

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.我对 API 进行了提取,现在我得到了存储在数组中的结果。 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 .我需要显示这个结果,但我尝试在返回中使用 for{} 并且它不起作用,我也尝试使用 .map 并且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>
        )
   }
}

The array is this:数组是这样的: 控制台中的模型数组

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.模型数组是从fetch返回的 json 的results ,因此您可以将其设置为状态中的models ,并将isLoaded设置为true以便在加载模型时隐藏加载指示器。

Example例子

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>;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM