我如何在React中的不同文件之间共享变量数据 [英] How can I share variable data across different files in React

查看:134
本文介绍了我如何在React中的不同文件之间共享变量数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的股市项目中设置图形.我正在尝试显示盖茨比中点击的股票的图表.

I am trying to set up graphs in my stockmarket project. I am trying to display the graph of the stock clicked on in Gatsby.

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

Currently, I can display the stock graph of any stock by manually typing in the stock name to the code. I would like to replace the stock name with ${query} inside of the url of the api call because of const query = event.target.value in index.js. So the searched term will be saved as query and I need to have access to the same variable in my other file chartData.js so that I can change my API call from let API_CALL = `https://cloud.iexapis.com/stable/stock/aapl/chart/5y?token=${API_KEY}`; into let API_CALL = `https://cloud.iexapis.com/stable/stock/${query}/chart/5y?token=${API_KEY}`; Thus I will have access to whichever term is searched and be able to turn it into a graph.

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

I thought maybe I could use state to do this, like moving query to state via query: this.state.value or query: {this.state.value}. Both of these returned errors so I figured that would not work (or I was doing it wrong at least).

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

chartData.js

chartData.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函数传递给应用程序中的其他组件.

In React if you need to share data between components the best approach is to use state and props to communicate the data. In this case your best bet is probably to store whatever variables you need to share as state in your parent or root component, then you can pass both the state data and setter functions to another other components in your app through properties.

例如:

    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文档中推荐的官方方法,请参见

This is the official approach recommend in the official React docs, see section The Data Flows Down section.

这篇关于我如何在React中的不同文件之间共享变量数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆