本文介绍了渲染方法,流星反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在遵循流星网站上的入门教程之后,我停在"2.4创建应用程序组件"项附近,首先进行安装:

After following the getting started tutorial on the meteor website i stopped around the item "2.4 Create App component", first install:

meteor add http

该应用程序的目的是以不同方式可视化纽约州的彩票api数据.

The app purpose is to visualize in differently the lottery api data of the state of New York.

import React, { Component } from 'react';
import { HTTP } from 'meteor/http';

var apiUrl = 'https://data.ny.gov/api/views/dg63-4siq/rows.json';

export default class App extends Component {

  numbers() {
    HTTP.get(apiUrl, {}, function(err, res){
        if(err){
            console.log('ERROR @ CALL');
        } else {
            console.log(res);
            return res.data.data.slice(-50).map((result, index) =>
            <li key={ result[0] }>{`${result[8]} - ${result[9]}`}</li>
            );
        }
    });
  }

  render() {
    return (
      <div className="container">
        <header>
          <h1>Numbers</h1>
        </header>
        <ul>
          { this.numbers() }
        </ul>
      </div>
    );
  }
}

http调用中的对象显示在控制台上,而不显示在DOM上

the object from the http call shows up on the console but not on the DOM

推荐答案

我认为在render函数中调用进行API调用的函数不是一个好主意,因为每次组件渲染时都会调用该函数.更好的地方是将它放在componentDidMount函数中,并将结果保存在状态中.如果您希望重复通话,请在setInterval函数中进行操作,例如

I don't think its a good idea to call the functions that makes an API call in the render function as it will be called everytime the component renders, a better place will be to have it in the componentDidMount function and save the result in state. If you want the call to repeat, do it in setInterval function like

export default class App extends Component {
  state = {data: []}
  componentDidMount() {
    var comp = [...this.state.comp]
    this.interval = setInterval(()=> {
      HTTP.get(apiUrl, {}, function(err, res){
        if(err){
            console.log('ERROR @ CALL');
        } else {
            console.log(res);
            this.setState({data: res.data.data.slice(-50)})

        }
        }.bind(this));
     }, 2000)

  }
  componentWillUnmount() {
       clearInterval(this.interval)
  }
  render() {
    return (
      <div className="container">
        <header>
          <h1>Numbers</h1>
        </header>
        <ul>
          {this.state.data.map((result, index) =>
             <li key={ result[0] }>{`${result[8]} - ${result[9]}`}</li>
            ); }
        </ul>
      </div>
    );
  }
}

这篇关于渲染方法,流星反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:52