Get Data From React Props
How to get data from props and be sure that data arrived properly. My issue is that in my class component I receive alarms from props and then I want to render table with the alarm
Solution 1:
It is bad practice to set initial values to state at the constructor, therefore use lifeCycles as componentDidMount or componentDidUpdate instead to manipulate the state.
export classHouseholdAlertsPureextendsReact.Component{
constructor(props) {
super(props);
// initial values for statethis.state = {
tableAlerts: [],
startDate: null,
endDate: null,
selectedSeverity: null,
isChecked: false
}
}
componentDidMount() {
// values declared for state at component first loadthis.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 changedif(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 stateif(!isChecked) {
this.setState( { tableAlerts: tableAlerts.filter((alert) => alert.setTimestamp < alert.clearTimestamp)} )
} else { this.setState({tableAlerts}) }
}
...rest class...
}
Now at render, { this.state.tableAlerts } should contain the correct information
Solution 2:
You should probably use componentDidUpdate
. It runs on each state and prop change.
This is an example of how it can be used:
componentDidUpdate(prevProps) {
if(this.props.householdAlerts !== prevProps.householdAlerts) {
this.setState({ tableAlerts: this.props.householdAlerts })
}
}
Post a Comment for "Get Data From React Props"