Javascript 使用Gatsby中的Link发送API数据

Javascript 使用Gatsby中的Link发送API数据,javascript,reactjs,gatsby,Javascript,Reactjs,Gatsby,我正在使用盖茨比和股票市场API制作一个股票投资组合项目。目前,当您按股票代码搜索时,它会返回表中的股票代码、市值和上一次收盘。当你点击返回的股票代码时,它会将你带到另一个页面。在下一页中,我希望能够访问相同的API搜索,以便显示股票的更多详细信息 昨晚在StackOverflow上我被告知我可以通过Link发送API数据,但是在查看了一些文档之后,我不确定如何具体实现我所描述的内容 我不介意将details.js切换到一个类组件,我之前已经尝试过了,并设置了state,但我只是遇到了大量不同的

我正在使用盖茨比和股票市场API制作一个股票投资组合项目。目前,当您按股票代码搜索时,它会返回表中的股票代码、市值和上一次收盘。当你点击返回的股票代码时,它会将你带到另一个页面。在下一页中,我希望能够访问相同的API搜索,以便显示股票的更多详细信息

昨晚在StackOverflow上我被告知我可以通过Link发送API数据,但是在查看了一些文档之后,我不确定如何具体实现我所描述的内容

我不介意将details.js切换到一个类组件,我之前已经尝试过了,并设置了state,但我只是遇到了大量不同的错误

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"

export default class index extends React.Component {
  state = {
      companyName: "",
      previousClose: "",
      marketCap: "",
      change: "",
      symbol: "",
      topStocks: []

  }


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



  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, query: `yourQuery`}}>{this.state.symbol}</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>
          </Layout>
      )
  }
}



这里有一些东西,因为你有一个奇怪的组件/页面

  • 您没有在
    details.js
    页面中导入
    useffect
    ,错误显示:

    未定义7:5错误“useEffect”

  • 通过
    组件传递的状态需要通过
    道具
    检索(或者分解
    道具
    并直接获取
    位置

  • details.js
    是一个功能组件,您没有
    setState
    (也没有
    this
    )功能。改用
    useState
    hook

  • query
    参数从未提供给此组件。一旦你解决了主要问题,你应该通过
    props
    传递它

    未定义错误“查询”

  • 您的部件没有套上骆驼套

  • 所有错误应通过以下方式修复:

    //import { Link } from "gatsby"
    import axios from 'axios';
    import React, { useEffect, useState } from 'react';
    import Layout from '../components/layout';
    
    const Details = props => {
      const [yourState, setYourState] = useState('');
      useEffect(() => {
        if (props.location.state.someState) {
          axios.get(`https://cloud.iexapis.com/stable/stock/${props.location.state.query}/quote?token=*****************`)
            .then(res => setYourState(res))
        }
      }, []);
    
      return <Layout>
        <div>
          {/*do stuff with your yourState. (i.e: console.log('hi!', yourState))*/}
            </div>
          </Layout>;
        };
    
    export default Details;
    
    //从“盖茨比”导入{Link}
    从“axios”导入axios;
    从“React”导入React,{useffect,useState};
    从“../components/Layout”导入布局;
    const Details=props=>{
    const[yourState,setYourState]=useState(“”);
    useffect(()=>{
    if(props.location.state.someState){
    axios.get(`https://cloud.iexapis.com/stable/stock/${props.location.state.query}/quote?标记=******************`)
    .然后(res=>setYourState(res))
    }
    }, []);
    回来
    {/*用你的yourState做些事情。(即:console.log('hi!',yourState))*/}
    ;
    };
    导出默认详细信息;
    
    关于第二点和第三点:

  • const Details=props=>{}
    等于
    const Details=({location})=>{}
    。 这种解构为您节省了一个步骤,可以直接获取
    location
    对象,而不是在您的条件下执行
    props.location
  • 功能组件中不允许使用
    setState
    函数,而类组件中不允许使用此函数。这完全取决于你选择一个还是另一个,但你需要意识到它们的“局限性”和“好处”。在这种情况下,您需要使用
    useState
    hook。如您所见,它由
    const[yourState,setYourState]
    组成。第二个元素(
    setYourState
    )是用于存储
    yourState
    值的函数,因此,axios异步请求将使用
    setYourState
    函数存储,并通过
    yourState
    检索。当然,你可以随意命名
  • index.js
    ,更新状态并设置
    查询
  • 推荐阅读资料:


    如果您需要任何一点的详细解释,请让我知道,我会提供。

    评论不用于进一步讨论;这段对话已经结束。
    D:\Web Development\React JS course\gatsby-site\src\pages\details.js
      7:5   error  React Hook "useEffect" is called in function "details" which is neither a React function component or a custom React Hook function  react-hooks/rules-of-hooks
      7:5   error  'useEffect' is not defined                                                                                                          no-undef
      8:12  error  Unexpected use of 'location'                                                                                                        no-restricted-globals
      9:65  error  'query' is not defined                                                                                                              no-undef
    
    ✖ 4 problems (4 errors, 0 warnings)
    
    //import { Link } from "gatsby"
    import axios from 'axios';
    import React, { useEffect, useState } from 'react';
    import Layout from '../components/layout';
    
    const Details = props => {
      const [yourState, setYourState] = useState('');
      useEffect(() => {
        if (props.location.state.someState) {
          axios.get(`https://cloud.iexapis.com/stable/stock/${props.location.state.query}/quote?token=*****************`)
            .then(res => setYourState(res))
        }
      }, []);
    
      return <Layout>
        <div>
          {/*do stuff with your yourState. (i.e: console.log('hi!', yourState))*/}
            </div>
          </Layout>;
        };
    
    export default Details;