我有一个仪表板,其中正在使用搜索字段过滤数据。关于状态数据的更改,我想重新加载已通过状态属性作为数据值的图形组件。
const intialState = {
graphData: null,
costCenterList: [],
costCenterValue: []
};
class Dashboard extends Component {
constructor(props){
super(props);
this.state = intialState;
this.handleCostCenterChange = this.handleCostCenterChange.bind(this);
}
handleCostCenterChange(event, values){
var filtered = this.state.graphData.filter(el => values.includes(el.costCode));
this.setState({graphData: filtered});
}
render() {
<Grid item md={2}>
<div>
<InputLabel id="costCenterLabel" style= {{textAlign:'left', fontWeight:'bold'}}>Cost Center</InputLabel>
<FormControl style={{minWidth:'200px', width:'100%'}} variant="outlined" >
<Autocomplete
multiple
options={this.state.costCenterList.map((p) => p)}
renderInput={params => (
<TextField {...params} margin="normal" variant="outlined" fullWidth autoComplete="off" />
)}
onChange={this.handleCostCenterChange}
/>
</FormControl>
</div>
</Grid>
<Grid item md={12}>
<BarGraph graphData={this.state.graphData}/>
</Grid>
}
}
BarGraph的代码如下:
export default class BarGraph extends Component {
state = {
dataForChart: {
datasets: [
]
}
}
render() {
return (
<div>
<h3>Hours Per Cost Center</h3>
<Bar ref="chart" data={this.state.dataForChart} options = {this.state.barChartOptions} height={242} width={486}/>
</div>
);
}
componentDidMount() {
try {
let graphData = this.props.graphData;
let newState = Object.assign({}, this.state);
newState.dataForChart.datasets =[{barPercentage: 1, label:'Hours Per Cost Center ', data : graphData, backgroundColor : oBarColours, borderWidth:2, borderColor:oBarColours}];
newState.dataForChart.labels = oCostCenterDistinct;
this.setState(newState);
} catch (error) {
console.log("Network error: " + error);
}
}
}
我想根据状态的graphData的变化来更新组件。在使用this.setState进行更改时,其状态更新值,但不包含新数据。
有人可以帮助我在这里丢失的内容吗?
答案 0 :(得分:4)
需要响应道具更新。将数据处理分解到一个实用程序函数中,该函数会在组件安装时调用,然后再次更新为道具。
export default class BarGraph extends Component {
state = {
dataForChart: {
datasets: []
}
};
setData() {
try {
const { graphData } = this.props;
const newState = { ...this.state };
newState.dataForChart.datasets = [
{
barPercentage: 1,
label: "Hours Per Cost Center ",
data: graphData,
backgroundColor: oBarColours,
borderWidth: 2,
borderColor: oBarColours
}
];
newState.dataForChart.labels = oCostCenterDistinct;
this.setState(newState);
} catch (error) {
console.log("Network error: " + error);
}
}
componentDidMount() {
this.setData();
}
componentDidUpdate(prevProps) {
if (prevProps.graphData !== this.props.graphData) {
this.setData();
}
}
render() {
return (
<div>
<h3>Hours Per Cost Center</h3>
<Bar
ref="chart"
data={this.state.dataForChart}
options={this.state.barChartOptions}
height={242}
width={486}
/>
</div>
);
}
}