简体   繁体   English

基本的reactjs,如何获取REST数据并将其呈现

[英]basic reactjs, how to get REST data and render it

I have a basic rect component and I already figured out how to get data from a protected rest api, however I am not sure how to render it in the component and how to call that function, or in which lifecycle I should call the function. 我有一个基本的rect组件,我已经弄清楚了如何从受保护的rest api获取数据,但是我不确定如何在该组件中呈现数据以及如何调用该函数,或者我应该在哪个生命周期中调用该函数。

import React, { Component } from 'react';
import LayoutContentWrapper from '../components/utility/layoutWrapper';
import LayoutContent from '../components/utility/layoutContent';
var q = require('q');

var Adal = require('../adal-webapi/adal-request');

function getValues() {
    var deferred = q.defer();
    Adal.adalRequest({
      url: 'https://abc.azurewebsites.net/api/values'
    }).then(function(data) {
      console.log(data);
    }, function(err) {
      deferred.reject(err);
    });
    return deferred.promise;
  }

export default class extends Component {



  render() {
    return (
      <LayoutContentWrapper style={{ height: '100vh' }}>
        <LayoutContent>
          <h1>Test Page</h1>
        </LayoutContent>
      </LayoutContentWrapper>
    );
  }
}

something like this... 像这样的东西

export default class extends React.Component {
  constructor(props) {
    super(props);
    // initialize myData to prevent render from running map on undefined
    this.state = {myData: []};
  }

  // use componentDidMount lifecycle method to call function
  componentDidMount() {
    // call your function here, and on promise execute `setState` callback
    getValues()
      .then(data => {
        this.setState({myData: data})
      }
  }

  render() {
    // create a list
    const items = this.state.myData.map((datum) => {
      return <LayoutContent>
        <h1>{datum}</h1>
      </LayoutContent>
   });

    // return with the list
    return (
      <LayoutContentWrapper style={{ height: '100vh' }}>
        {items}
      </LayoutContentWrapper>
    );
  }
}

The lifecycle method you choose to fetch the data in will largely depend on whether or not you need to update the data at any point and re-render, or whether that data depends on any props passed to the component. 您选择用来获取数据的生命周期方法将在很大程度上取决于您是否需要在任何时候更新数据并重新呈现,或者该数据是否取决于传递给组件的任何道具。

Your example looks as though it is a one time API call that doesn't depend on any props, so placing it in the constructor would be valid. 您的示例似乎是一次不依赖任何道具的API调用,因此将其放置在构造函数中将是有效的。

I would move the getValues code to within the class, and do something like this. 我将把getValues代码移到该类中,并执行类似的操作。 Note: I've used async/await, but you could use promise callbacks if you prefer. 注意:我使用了async / await,但是如果愿意,可以使用promise回调。

export default class MyComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        }
        this.fetchData();
    }

    async fetchData() {
        try {
            const data = await this.getValues();
            !this.isCancelled && this.setState({ data });
        } catch(error) {
            // Handle accordingly
        }
    }

    getValues() { 
        // Your API calling code
    }

    componentWillUnmount() {
        this.isCancelled = true;
    }

    render() {
        const { data } = this.state;
        return (
            <ul>
                {data && data.map(item => (
                    <li>{item.name}</li>
                ))}
            </ul>
        );
    }
}

If you needed to fetch the data again at any point, you might use one of the other lifecycle hooks to listen for prop changes, and call the fetchData method again. 如果您需要在任何时候再次获取数据,则可以使用其他生命周期挂钩之一来侦听fetchData更改,然后再次调用fetchData方法。

Note the inclusion of a failsafe for the component un-mounting before the async call has finished, preventing React from throwing an error about setting state in an unmounted component. 请注意,在异步调用完成之前为组件的卸载提供了一个故障保护,以防止React引发有关在已卸载的组件中设置状态的错误。

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

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