reactjs - 如何在 React 中的不同文件之间共享变量数据

标签 reactjs gatsby

我正在尝试在我的股票市场项目中设置图表。我正在尝试显示在 Gatsby 中点击的股票的图表。

目前,我可以通过在代码中手动输入股票名称来显示任何股票的股票图表。我想用 api 调用的 url 内的 ${query} 替换股票名称,因为 const query = event.target.valueindex.js 。因此,搜索的术语将保存为查询,我需要访问其他文件 chartData.js 中的相同变量这样我就可以从 let API_CALL = `https://cloud.iexapis.com/stable/stock/aapl/chart/5y?token=${API_KEY}`; 更改我的 API 调用进入let API_CALL = `https://cloud.iexapis.com/stable/stock/${query}/chart/5y?token=${API_KEY}`;因此,我将可以访问搜索到的任何术语,并能够将其转换为图表。

我想也许我可以使用状态来做到这一点,比如通过 query: this.state.value 将查询移动到状态或query: {this.state.value} 。这两个都返回了错误,所以我认为这是行不通的(或者至少我做错了)。

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: [],
      Yearweekhigh: "",
      Yearweeklow: "",
      avgTotalVolume: "",
      peRatio: "",
      

  }
     
  

  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>


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

图表数据.js

import React from 'react'
import Plot from 'react-plotly.js'

class Stock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            stockChartXValues: [],
            stockChartYValues: [],
        };
    }

    componentDidMount() {
        this.fetchStock();
    }

    fetchStock() {
        const pointerToThis = this;
        const API_KEY = '**************************';
        let API_CALL = `https://cloud.iexapis.com/stable/stock/aapl/chart/5y?token=${API_KEY}`;
        let stockChartXValuesFunction = [];
        let stockChartYValuesFunction = [];

        fetch(API_CALL)
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {

            for (var x in data) {
                stockChartXValuesFunction.push(x);
                stockChartYValuesFunction.push(
                    data[x]['uOpen']
                );

                pointerToThis.setState({
                    stockChartXValues: stockChartXValuesFunction,
                    stockChartYValues: stockChartYValuesFunction,
                });
            }


        })
    }


    render() {
        return (
            <div>
                <Plot
                data={[
                    {
                        x: this.state.stockChartXValues,
                        y: this.state.stockChartYValues,
                        type: "scatter",
                        mode: "lines+markers",
                        marker: {color: "red"}
                    },
                ]}
                layout={{ width: 720, height: 440, title: "A Fancy Plot"}}
                />
            </div>
        )
    }
}

export default Stock

最佳答案

在 React 中,如果需要在组件之间共享数据,最好的方法是使用 stateprops 来通信数据。在这种情况下,最好的选择可能是将需要作为状态共享的任何变量存储在父组件或根组件中,然后您可以通过属性将状态数据和 setter 函数传递给应用程序中的其他组件。

例如:

    function Welcome(props) {
      return <h1>Hello, {props.name}</h1>;
    }

    function Bye(props) {
      return <h1>Bye, {props.name}</h1>;
    }

    function App() {
        constructor(props) {
          super(props);
          this.state = {
              name: '',
          };
        }
      return (
        <div>
          <Welcome name="Sara" />
          <Welcome name="Cahal" />
          <Bye name="Edite" />
        </div>
      );
    }

这是React官方文档中推荐的官方方法,请参阅The Data Flows Down部分部分。

关于reactjs - 如何在 React 中的不同文件之间共享变量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63005503/

相关文章:

Facebook 无法识别 Netlify 上的一些 Gatsby React Helmet 元标签

css - 如何将我的::元素悬停在样式化的组件中

reactjs - 如何使用 React js 处理非常大的文件下载

node.js - 如何在aws ec2(linux实例)上部署Next js

reactjs - react 钩悬停效果

javascript - 带有 Iframe 事件和更改处理的 ReactJs

graphql - 如何在graphql查询过滤器中使用OR/AND或使大小写不敏感的过滤器?

reactjs - create-react-app 的 ES6 Polyfill 不起作用

reactjs - 来自react-transition-group的CSSTransition不应用类

reactjs - google 域上 netlify 的 DNS 设置是什么?