簡體   English   中英

如何顯示/隱藏獲取的 array.map() 的 React 元素

[英]How to show/hide React element of fetched array.map()

我想根據onClickShowChart state 屬性和 output 顯示/隱藏 JSX 的一部分基於 ID 的正確圖表數據。

但這部分在 map 循環內,當我單擊顯示元素時,它將根據 ID 獲取數據,然后返回數組並顯示圖表。

挑戰
問題是每次我點擊顯示圖表時,每個映射項目都會顯示相同的圖表數據,因為它取決於相同的 state 屬性。 我無法設置單獨的 state 因為它使用array.map() function 循環所有記錄。

如何單獨顯示/隱藏正確的圖表數據而不影響並保留其他記錄 state 和圖表數據?

 constructor(props) {
    super(props);
    // Initial states
    this.state = { dataList[], showChart: false, showChartData: [] }
 }

componentWillmount() {
 this._getDataList()
}

 _getDataList() {
      axios.get(`.../List`,
        {
          params: { id: id },
          headers: { 'Authorization': ...accessToken }
        }).then((res) => {
          this.setState({ dataList: res.data })
        })
   })

 onClickShowChart = (id) => {
    this.setState({ showChart: true }, () => this._getGraphData(id))
 }

 // When click to show, it will fetch graph data and then pass to state
 _getGraphData(id) {
      axios.get(`.../productAdsStatistic`,
        {
          params: { id: id },
          headers: { 'Authorization': ...accessToken }
        }).then((res) => {
          this.setState({ graphData: res.data })
        })
   })

 renderChart() {
    return (
      <Chart data={this.state.graphData}>
       // ...
      </Chart>
    )
 }

 render() {
   return (
     <div>
       <Row>
         <Col>
           {this.state.dataList.map((v) => {
             <h1>{v.title}<h1>
             <span onClick={() => this.onClickShowChart(v._id)}>
               Click to show chart
             </span>
             <Row>
               <Col>{this.state.showChart === true ? renderChart() : ''}</Col>
             </Row>
           }
         </Col>
       </Row>
     </div>
   }
 }

JSON 數組結果來自 API

[
 {
  _id: C1,
  title: Chart A
 },
 {
  _id: C2,
  title: Chart B
 }
]

圖表數據 JSON 1 個圖表的 API 的數組結果

[
  {
    month: "Jan",
    value: 7
  },
  {
    month: "Feb",
    value: 6.9
  }
]

以下是沙盒鏈接:

https://codesandbox.io/s/ancient-snow-ne0gv?file=/src/DataList.js

Class 版本以上解決方案:

https://codesandbox.io/s/tender-dream-xy3vm

擴展我在評論中提到的想法:只需維護一個單獨的 state 變量,它將存儲被點擊的 dataList 中的項目索引。 並且 renderChart 應該接受一個對應於 rowIndex 的參數。 在 renderChart function 檢查上面 state 索引數組中是否存在 rowIndex,如果存在,則渲染圖表,否則為 null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM