Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

153
Visualizações
Reaccionar datos de Javascript APi que no llenan una matriz antes de renderizar

Intento representar un componente de gráfico de líneas en una página. Puedo obtener los datos en la página principal que no se muestran aquí, pero cuando intento obtener los datos de API en el componente, la matriz se devuelve vacía. mi código es el siguiente:

Soy nuevo en Javascript, así que me pregunto si estoy haciendo esto en el orden incorrecto.

 import React from 'react'; import NVD3Chart from 'react-nvd3'; function getDatum() { const alpha = require('api')({ key: 'xxxxxxxxxxxxxxx' }); var array = []; var newArray = []; alpha.data.intraday(`msft`).then((data) => { const polished = alpha.util.polish(data); {Object.keys(polished.data).map((key) => ( array.push(polished.data[key].open) ))} }); for (let index = 0; index < array.length; index++) { const element = array[index]; newArray.push({ 'x': index, 'y': parseFloat(element) }) } return [ { values: newArray, key: 'OpenPrice', color: '#A389D4' } ]; } class LineChart extends React.Component { static data; constructor(props) { super(props); this.state = { DataisLoaded: false, }; } componentDidMount() { const { DataisLoaded } = this.state; this.setState({ DataisLoaded: true }); LineChart.data = getDatum(); } render() { const { DataisLoaded } = this.state; if (!DataisLoaded) return <div> <h1> Please wait some time.... </h1> </div> ; console.log(LineChart.data) return ( <div> { React.createElement(NVD3Chart, { xAxis: { tickFormat: function(d){ return d; }, axisLabel: 'Time (ms)' }, yAxis: { axisLabel: 'Voltage (v)', tickFormat: function(d) {return parseFloat(d).toFixed(2); } }, type:'lineChart', datum: LineChart.data, x: 'x', y: 'y', height: 300, renderEnd: function(){ console.log('renderEnd'); } }) } </div> ) } } export default LineChart;

Necesito poder trabajar con estos datos, por lo que cualquier ayuda sería muy apreciada.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Creo que lo que sucede es que en la función getDatum , la declaración de return se ejecuta antes de que se resuelva la promesa .then() . Además, normalmente cualquier dato que desee representar en un componente se almacena en el estado de reacción.

Prueba algo como esto:

 import React from 'react'; import NVD3Chart from 'react-nvd3'; function getDatum(setState, lineChart) { const alpha = require('api')({ key: 'xxxxxxxxxxxxxxx' }); var array = []; var newArray = []; alpha.data.intraday(`msft`).then((data) => { const polished = alpha.util.polish(data); {Object.keys(polished.data).map((key) => ( array.push(polished.data[key].open) ))} for (let index = 0; index < array.length; index++) { const element = array[index]; newArray.push({ 'x': index, 'y': parseFloat(element) }) } // If you need data from the previous state one way to do it is to merge in lineChart with this state, but I'm not sure where you'd do it because I'm not sure where .data is coming from. setState([ { values: newArray, key: 'OpenPrice', color: '#A389D4' } ]) }); } class LineChart extends React.Component { static data; constructor(props) { super(props); this.state = { DataisLoaded: false, lineChart: [] }; } componentDidMount() { const { DataisLoaded, lineChart } = this.state; getDatum(this.setState, lineChart); this.setState({ DataisLoaded: true }); } render() { const { DataisLoaded, lineChart } = this.state; if (!DataisLoaded) return <div> <h1> Please wait some time.... </h1> </div> ; console.log(LineChart.data) return ( <div> { React.createElement(NVD3Chart, { xAxis: { tickFormat: function(d){ return d; }, axisLabel: 'Time (ms)' }, yAxis: { axisLabel: 'Voltage (v)', tickFormat: function(d) {return parseFloat(d).toFixed(2); } }, type:'lineChart', datum: lineChart.data, // I don't really know where .data is coming from?? x: 'x', y: 'y', height: 300, renderEnd: function(){ console.log('renderEnd'); } }) } </div> ) } } export default LineChart;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda