Show fetch results in render return() in React.js

回眸只為那壹抹淺笑 提交于 2019-12-13 14:24:23

问题


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

The array is this:


回答1:


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.

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


来源:https://stackoverflow.com/questions/51522379/show-fetch-results-in-render-return-in-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!