2 回答
TA贡献1831条经验 获得超4个赞
在构造函数中将初始值设置为状态是不好的做法,因此使用 lifeCycles 作为 componentDidMount 或 componentDidUpdate 来操作状态。
export class HouseholdAlertsPure extends React.Component {
constructor(props) {
super(props);
// initial values for state
this.state = {
tableAlerts: [],
startDate: null,
endDate: null,
selectedSeverity: null,
isChecked: false
}
}
componentDidMount() {
// values declared for state at component first load
this.setState({
startDate: moment()
.subtract(30, 'days')
.startOf('day'),
endDate: moment().endOf('day'),
selectedSeverity: null,
isChecked: true,
tableAlerts: this.props.householdAlerts
});
componentDidUpdate() {
// called whenever prop value changed
if(this.props.householdAlerts !== this.state.tableAlerts)
this.setState({ tableAlerts: this.props.householdAlerts })
}
selectOngoingAlerts = (e, data) => {
const { isChecked, tableAlerts } = this.state;
this.setState( {isChecked : !isChecked} );
// right now, { isChecked } still refer to construct abouve methond and prev value...
// for more consist aproach, consider do the filtering logic direct at render without manipulate state
if(!isChecked) {
this.setState( { tableAlerts: tableAlerts.filter((alert) => alert.setTimestamp < alert.clearTimestamp)} )
} else { this.setState({tableAlerts}) }
}
...rest class...
}
现在在渲染时,{ this.state.tableAlerts } 应该包含正确的信息
TA贡献1828条经验 获得超3个赞
您可能应该使用componentDidUpdate. 它在每个状态和道具更改上运行。
这是如何使用它的示例:
componentDidUpdate(prevProps) {
if(this.props.householdAlerts !== prevProps.householdAlerts) {
this.setState({ tableAlerts: this.props.householdAlerts })
}
}
添加回答
举报