我想再次从子组件中单击一个按钮,然后从先前状态清除子状态。
父组件
constructor() {
super();
this.state = {
events:[],
alerts:[],
};
}
addEvent = newEvent => this.setState(state => {
const {events} = state
return { events: [...events, ...newEvent]}
});
addAlert = newAlert => this.setState(state =>{
const {alerts} = state
return {alerts: [...alerts, ...newAlert]
});
render(){
const {events} = this.state
const {alerts} = this.state
console.log(alerts);
return(
<div >
<SearchFlight events={events} alerts={alerts} addAlert={this.addAlert} addEvent={this.addEvent} />
<Events events={events}/>
<Alerts alerts={alerts}/>
}
子组件
handleSubmit= event =>{
const {addEvent} = this.props
const {addAlert} = this.props
event.preventDefault();
//alert(this.state.search_flight_no);
var airportValueSelected= this.state.airport;
var flightValue= this.state.search_flight_no;
var airportList= FlightInfo.Airport;
var newEvents=[];
var newAlerts=[];
for(var rootKey in airportList){
if(rootKey===airportValueSelected)
{
airportList[rootKey].forEach(element => {
if(element.flight_no===flightValue){
for(var m=0;m<element.Events.length;m++){
var singleEvent={
event_name:'',
date_time:'',
};
singleEvent.event_name=element.Events[m].event_name;
singleEvent.date_time=element.Events[m].date_time;
newEvents.push(singleEvent);
}
for(var s=0;s<element.Alerts.length;s++){
newAlerts.push(element.Alerts[s]["Alert"+(s+1)]);
}
}
});
if(newEvents.length<1 && newAlerts.length<1){
this.setState({ open: true });
}
else{
console.log(newEvents);
console.log(newAlerts);
}
addAlert(newAlerts);
addEvent(newEvents);
}
}
当我单击并调用 handleSubmit 方法时,它会继续添加事件和警报,而不是将其设置为空,并存储新值,而附加以前的状态价值观。
答案 0 :(得分:1)
addEvents和addAlerts附加值的原因是因为您只是将当前值设置为state,而是使用传播语法将其附加到setState调用中。您只需要写
addEvent = newEvent => this.setState({
events: newEvent
});
addAlert = newAlert => this.setState({
alerts: newAlert
});