这是我的 SalesOverview1 组件。在用户单击“销售概览”选项卡后,我正在发出 axios 请求。 onClick 处理程序的代码位于父组件中,我更新状态以指示已进行单击,我基本上将状态更改为 true。然后我根据点击有条件地呈现 SalesOverview1 组件,然后在 componentDidMount 中,我发出 axios 请求。即使正在获取数据,我也无法在第一次点击时看到图表。但是当我点击另一个标签,然后再点击“销售概览”标签时,我可以看到它。
class SalesOverview1 extends Component {
state = {
page_id: 4,
hcp_id: 101,
sales_overview_data: []
}
componentDidMount() {
console.log('Clicked on sales Overview!');
let page_id = this.state.page_id;
let hcp_id = this.state.hcp_id;
console.log('state: ', this.state);
axios.post('/test-json', {
page_id: page_id,
hcp_id: hcp_id
})
.then((res) => {
const dataRequest = res.data;
console.log('State before loading data in sales overview: ', this.state);
console.log('received data inside sales overview', res.data);
this.setState({ ...this.state, sales_overview_data: res.data });
console.log('State after loading data in sales overview: ', this.state);
// this.props.salesOverviewDataFromParent(this.state.sales_overview_data);
this.forceUpdate();
}, (error) => {
console.log(error);
});
}
return(
<>
<div role="tabpanel" id="tablet-3" class="tab-pane" >
<div class="panel-body" style={{ backgroundColor: "rgb(243,243,244)", border: "none", margin: 0 }}>
<div class='row'>
{
this.state.sales_overview_data.length !== 0 &&
<ChartBox
data={this.state.sales_overview_data[401]}
/>
}
</div>
</div>
</div>
这个组件在父 Search 组件中是这样触发的:
class Search{
state={
sales_overview_clicked: false
}
...
salesOverviewButtonClicked = () => {
this.setState({ ...this.state, sales_overview_clicked: true })
}
return(
<div>
<ul class="nav nav-tabs" role="tablist">
<li><a class="nav-link " data-toggle="tab" href="#tablet-3" onClick={this.salesOverviewButtonClicked}> <i class="fa fa-bar-chart-o"></i>Sales Overview</a></li>
</ul>
<div class="tab-content">
{this.state.sales_overview_clicked === true && <SalesOverview1 />}
</div>
</div>
我只保留了相关代码并删除了不需要的代码。
“销售概览”选项卡的外观: