【问题标题】:Passing variables in JSX在 JSX 中传递变量
【发布时间】:2020-08-10 21:35:02
【问题描述】:

我有一个函数,我使用setStockData 发送获取请求并存储返回的数据,代码的基本分解如下。

  function LoggedIN(){
      const [stockData, setStockData] = useState([]); // Data from the API search

       // 
      // Set the stockData from a fetch in this area 
     //

      return (
        <Graphdraw /> 
      );
    }

stockData 变量在设置后看起来基本上是这样的。

[
  {
    "timestamp": "2020-03-19T14:00:00.000Z",
    "symbol": "AAL",
    "name": "American Airlines Group",
    "open": 11.6,
    "high": 12.16,
    "low": 10.01,
    "close": 10.29,
  },
  {
    "timestamp": "2020-03-18T14:00:00.000Z",
    "symbol": "AAL",
    "name": "American Airlines Group",
    "open": 14.24,
    "high": 14.28,
    "low": 10.17,
    "close": 11.65,
  }
]

我想将stockData 传递给&lt;Graphdraw /&gt;,这样我就可以像下面这样访问它

function Graphdraw(props){

  for (let i = 0; i < props.length; i++){
    console.log(props[i].low);
  }

}

到目前为止,我阅读了一些帖子并查看了 jsx 页面,但似乎无法正确通过。我如何将stockData 传递到&lt;Graphdraw /&gt; 并且我是否在function Graphdraw (props) 中正确访问它?

【问题讨论】:

    标签: javascript jsx use-state


    【解决方案1】:

    试试这个?

    function LoggedIN(){
      const [stockData, setStockData] = useState([]); // Data from the API search
    
       // 
      // Set the stockData from a fetch in this area 
     //
    
      return (
        <Graphdraw stockData={stockData} /> 
      );
    }
    
    function Graphdraw(props){
      for (let i = 0; i < props.stockData.length; i++){
         console.log(props.stockData[i].low);
      } 
    }
    

    【讨论】:

    • 请解释为什么有人反对我的回答?
    • 好的没问题
    【解决方案2】:

    你这样传递它:

    return (
        <Graphdraw stockData={stockData} /> 
    );
    

    Graphdraw 中,您可以以props.stockData 访问它,尽管在参数列表中使用解构很常见,因此您可以只使用stockData

    function Graphdraw({stockData}) {
        // ...use `stockData` here...
    }
    

    the tutorial 中的详细信息。

    【讨论】:

      猜你喜欢
      • 2018-06-13
      • 2022-01-22
      • 2013-12-25
      • 2017-05-22
      • 2020-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多