[英]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.