将点击的链接保存为查询以搜索 API(React、Gatsby)

我正在使用 Gatsby 和股票市场 API 来制作股票投资组合应用程序。目前,我已对其进行了设置,以便当您通过股票代码搜索股票时,它会返回股票代码、市值和上一个收盘价。我还这样做了,当您单击股票代码时,它会将您带到另一个 Gatsby 页面。在下一页上,我希望它为您提供有关股票的更多数据的表格。


我需要的功能是搜索在新选项卡中单击的股票代码,以便我可以设置更详细的表格。


index.js


import React from "react"

import { Link } from "gatsby"

import axios from "axios"

import "../css/style.css"

import Layout from "../components/layout"


export default class index extends React.Component {

  state = {

      companyName: "",

      previousClose: "",

      marketCap: "",

      change: "",

      symbol: ""


  }



  componentDidMount() {

    const API_KEY = '************************';

    axios.get(`https://cloud.iexapis.com/stable/stock/XOM/quote?token=${API_KEY}`)

      .then(res => {

        const symbol = res.data['symbol'];

        this.setState({ symbol })


        const previousClose = res.data['previousClose'];

        this.setState({ previousClose })


        const marketCap = res.data['marketCap'];

        this.setState({ marketCap })

      })

  }


  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 })

          })

      }

  }

交互式爱情
浏览 101回答 1
1回答

回首忆惘然

<Link>您可以使用对象通过组件传递数据state,如Gatsby 的 Link API 文档所示:<td><Link&nbsp;to="/details"&nbsp;state=={{someState:'hello'}}>{this.state.symbol}</Link</td>然后,details.js您将收到以下内容作为道具(存储在 中location.state.someState):export default function details() {&nbsp; &nbsp; useEffect(()=>{&nbsp; &nbsp; &nbsp; &nbsp; if(location.state.someState){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //your axios async query&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <Layout>&nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; </Layout>&nbsp; &nbsp; )}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript