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