Javascript 在Gatsby中发送API数据以用于Chart.js
我正在尝试将调用的API数据从index.js发送到ChartData.js。index.js是一个页面,ChartData.js是Gatsby中的一个组件,因此首先我无法确定Gatsby的Link to=”“函数是否只能从一个页面发送到另一个页面,或者它是否可以将数据从一个页面发送到一个组件 问题是当我试图访问从index.js到ChartData.js的行Javascript 在Gatsby中发送API数据以用于Chart.js,javascript,reactjs,gatsby,Javascript,Reactjs,Gatsby,我正在尝试将调用的API数据从index.js发送到ChartData.js。index.js是一个页面,ChartData.js是Gatsby中的一个组件,因此首先我无法确定Gatsby的Link to=”“函数是否只能从一个页面发送到另一个页面,或者它是否可以将数据从一个页面发送到一个组件 问题是当我试图访问从index.js到ChartData.js的行{props.location.state.companyName}中发送的数据时,我收到错误:TypeError:props.locat
{props.location.state.companyName}
中发送的数据时,我收到错误:TypeError:props.location未定义
我计划把标签:['x','y']
换成标签:[{props.location.state.companyName},{props.location.state.symbol}
等。我不确定这是否是正确的语法
这里有更详细的解释:
index.js:
import React from "react"
import { Link } from "gatsby"
import axios from "axios"
import "../css/style.css"
import Layout from "../components/layout"
import { symbol } from "prop-types"
import ChartData from "../components/ChartData"
export default class index extends React.Component {
state = {
companyName: "",
previousClose: "",
marketCap: "",
change: "",
symbol: "",
topStocks: [],
Yearweekhigh: "",
Yearweeklow: "",
avgTotalVolume: "",
peRatio: ""
}
componentDidMount() {
const API_KEY = '*******************';
axios.get(`https://cloud.iexapis.com/stable/stock/market/previous?token=${API_KEY}`)
.then(res => {
console.log(res)
const topStocks = res.slice(1);
this.setState({ topStocks })
})
}
clickHandler = (event) => {
if (event.keyCode === 13) {
const query = event.target.value;
const API_KEY = '*******************';
axios.get(`https://cloud.iexapis.com/stable/stock/${query}/quote?token=${API_KEY}`)
.then(res => {
const companyName = res.data['companyName'];
this.setState({ companyName })
const previousClose = res.data['previousClose'];
this.setState({ previousClose })
const marketCap = res.data['marketCap'];
this.setState({ marketCap })
const change = res.data['change'];
this.setState({ change })
const symbol = res.data['symbol'];
this.setState({ symbol })
const Yearweekhigh = res.data['week52High'];
this.setState({ Yearweekhigh })
const Yearweeklow = res.data['week52Low'];
this.setState({ Yearweeklow })
const avgTotalVolume = res.data['avgTotalVolume'];
this.setState({ avgTotalVolume })
const peRatio = res.data['peRatio'];
this.setState({ peRatio })
})
}
}
render() {
return (
<Layout>
<div class = "main-div">
<input type="search" class="main-search" onKeyDown={event => this.clickHandler(event)}/>
<table>
<tr>
<th>Ticker-Symbol</th>
<th>Market Cap</th>
<th>Previous Close</th>
</tr>
<tr>
<td>
<Link to='/details/' state={{
setState: this.state.symbol,
companyName: this.state.companyName,
previousClose: this.state.previousClose,
marketCap: this.state.marketCap,
change: this.state.change,
Yearweekhigh: this.state.Yearweekhigh,
Yearweeklow: this.state.Yearweeklow,
avgTotalVolume: this.state.avgTotalVolume,
peRatio: this.state.peRatio
}}>
{this.state.symbol}</Link>
<Link to='/ChartData/' state={{
setState: this.state.symbol,
companyName: this.state.companyName,
previousClose: this.state.previousClose,
marketCap: this.state.marketCap,
change: this.state.change,
Yearweekhigh: this.state.Yearweekhigh,
Yearweeklow: this.state.Yearweeklow,
avgTotalVolume: this.state.avgTotalVolume,
peRatio: this.state.peRatio
}}></Link>
</td>
<td>{this.state.marketCap}</td>
<td>{this.state.previousClose}</td>
</tr>
</table>
</div>
<div>
{
this.state.topStocks.length && this.state.topStocks.map(stock => (
<h1>{stock.symbol}</h1>
))
}
</div>
<ChartData />
</Layout>
)
}
}
从“React”导入React
从“盖茨比”导入{Link}
从“axios”导入axios
导入“./css/style.css”
从“./组件/布局”导入布局
从“道具类型”导入{symbol}
从“./组件/ChartData”导入图表数据
导出默认类索引扩展React.Component{
状态={
公司名称:“,
上一次关闭:“,
市值:“,
更改:“,
符号:“,
顶杆:[],
Yearweekhigh:“,
年周刊:“,
平均总体积:“”,
手术:“
}
componentDidMount(){
常量API_KEY='********************';
axios.get(`https://cloud.iexapis.com/stable/stock/market/previous?token=${API_KEY}`)
。然后(res=>{
console.log(res)
const topStocks=res.slice(1);
this.setState({topStocks})
})
}
clickHandler=(事件)=>{
如果(event.keyCode===13){
const query=event.target.value;
常量API_KEY='********************';
axios.get(`https://cloud.iexapis.com/stable/stock/${query}/quote?标记=${API\U键}`)
。然后(res=>{
const companyName=res.data['companyName'];
this.setState({companyName})
const previousClose=res.data['previousClose'];
this.setState({previousClose})
const marketCap=res.data['marketCap'];
this.setState({marketCap})
const change=res.data['change'];
this.setState({change})
const symbol=res.data['symbol'];
this.setState({symbol})
const Yearweekhigh=分辨率数据['week52高];
this.setState({Yearweekhigh})
const Yearweeklow=res.data['week52Low'];
this.setState({Yearweeklow})
const avgTotalVolume=res.data['avgTotalVolume'];
this.setState({avgTotalVolume})
const peRatio=res.data['peRatio'];
this.setState({peRatio})
})
}
}
render(){
返回(
this.clickHandler(事件)}/>
股票代码
市值
前收盘
{this.state.symbol}
{this.state.marketCap}
{this.state.previousClose}
{
this.state.topStocks.length&&this.state.topStocks.map(stock=>(
{stock.symbol}
))
}
)
}
}
details.js
//import { Link } from "gatsby"
import axios from 'axios';
import React, { useEffect, useState } from 'react';
import Layout from '../components/layout';
import "../css/style.css"
const Details = props => {
const [yourState, setYourState] = useState('');
useEffect(() => {
}, []);
return <Layout>
<div>
<h1 class="details-company-name">{props.location.state.companyName}</h1>
<div class = "details-div">
<div class="details-div-1">
<p>Open {} </p>
<p>High {} </p>
<p>Low {} </p>
<p>52 WK HIGH <h2>{props.location.state.Yearweekhigh}</h2> </p>
<p>52 WK LOW <h2>{props.location.state.Yearweeklow}</h2> </p>
</div>
<div class="details-div-2">
<p>VOLUME</p>
<p>AVG VOL <h2>{props.location.state.avgTotalVolume}</h2> </p>
<p>MKT CAP <h2>{props.location.state.marketCap}</h2></p>
<p>P/E RATIO <h2>{props.location.state.peRatio}</h2></p>
<p>DIV/YIELD</p>
</div>
</div>
</div>
</Layout>;
};
export default Details;
//从“盖茨比”导入{Link}
从“axios”导入axios;
从“React”导入React,{useffect,useState};
从“../components/Layout”导入布局;
导入“./css/style.css”
const Details=props=>{
const[yourState,setYourState]=useState(“”);
useffect(()=>{
}, []);
返回
{props.location.state.companyName}
打开{}
高{}
低{}
52周高{props.location.state.Yearweekhigh}
52周低{props.location.state.Yearweeklow}
卷
AVG VOL{props.location.state.avgTotalVolume}
MKT CAP{props.location.state.marketCap}
市盈率{props.location.state.peractio}
部门/收益
;
};
导出默认详细信息;
ChartData.js
import React, {useState, useEffect } from "react";
import { Line } from "react-chartjs-2";
const ChartData = props => {
const [yourState, setYourState] = useState('');
const chart = () => {
setYourState({
labels: ['x', 'y'],
datasets: [
{
level: 'level of xyz',
data: [22, 55]
}
]
})
}
useEffect(() => {
chart()
}, [])
return(
<div>
<h1>Hello</h1>
{props.location.state.companyName}
<div>
<Line data={yourState}/>
</div>
</div>
)
}
export default ChartData;
从“React”导入React,{useState,useffect};
从“react-chartjs-2”导入{Line};
常量图表数据=道具=>{
const[yourState,setYourState]=useState(“”);
常数图=()=>{
设置你的状态({
标签:['x','y'],
数据集:[
{
级别:“xyz级别”,
数据:[22,55]
}
]
})
}
useffect(()=>{
图表()
}, [])
返回(
你好
{props.location.state.companyName}
)
}
导出默认图表数据;
这里有很多事情需要澄清。您在标题中提到了graphql,但代码中没有graphql
您正在使用在生命周期方法中的运行时获取数据,然后将结果设置为状态
我假设一旦你有了这些数据,你所要做的就是把它传递给你的图表组件,这样它就可以在索引页上显示自己
考虑下面的示例,它做同样的事情;从获取一些数据,将结果设置为状态,并通过props将状态的相关部分直接传递给
组件
从这里开始,
组件拥有渲染所需的一切。(它没有
// index.js
import React from 'react';
import './App.css';
import Characters from './Characters'
const api = "https://rickandmortyapi.com/api/character/";
class IndexPage extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch(api)
.then(res => res.json())
.then(
json => {
console.log(json)
this.setState({
isLoaded: true,
data: json.results
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, data } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<Characters data={data} />
);
}
}
}
export default IndexPage;
// Characters.js
import React from 'react';
class Characters extends React.Component {
render() {
return (
<ul>
{this.props.data.map(item => (
<li key={item.id}>
<dl>
<dt>Name:</dt>
<dd>{item.name}</dd>
<dt>Species:</dt>
<dd>{item.species}</dd>
<dt>Status:</dt>
<dd>{item.status}</dd>
</dl>
</li>
))}
</ul>
);
}
}
export default Characters;