gpt4 book ai didi

javascript - 在 Reactjs 中动态显示从一种状态到另一种状态的值

转载 作者:行者123 更新时间:2023-12-03 00:39:03 24 4
gpt4 key购买 nike

我有四个组件,分别命名为 UserHome、SearchFlight、Events 和 Alerts

我得到了 UserHome 组件,我正在其中导入所有组件

<SearchFlight/>
<Events />
<Alerts />

SearchFlight中,我有一个带有两个输入和一个按钮的表单。当我单击按钮时,我正在调用一个函数,该函数将为我提供的相应输入计算一些 JSON 值(事件警报数组),然后我想注入(inject)这些输入在事件和警报组件中动态

constructor() {
super();
this.state = {
open: false,
airport: '',
search_flight_no: '',
};

}

handleSubmit= event =>{
event.preventDefault();

var airportValueSelected= this.state.airport;
var flightValue= this.state.search_flight_no;
var airportList= FlightInfo.Airport;
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;
this.state.events.push(singleEvent);
}

for(var s=0;s<element.Alerts.length;s++){

this.state.alerts.push(element.Alerts[s]["Alert"+(s+1)]);

}

}
// Here I am getting both events and alerts arrays
});
if(this.state.events.length<1 && this.state.alerts.length<1){
this.setState({ open: true });
}
else{

}


}
}

此代码将获取事件和警报数组,因此我已对获取它的位置进行了评论。

这里是我的用户主页休息

 constructor() {
super();
this.state = {
events:[],
alerts:[],
};

}

setEvents = newEvents => this.setState({events: newEvents})


render(){
const {events} = this.state
return(
<div >
<div style={{display:'inline-block',minHeight:'470px',}}>
<div className="clearfix visible-xs"></div>
<div className="container">
<SearchFlight events={events} setEvents={this.setEvents} />
</div>
<div className="clearfix visible-xs"></div>
<button className="btn btn-primary" style={{position:'absolute',right:'0',top:'62px',}}>
<Link to={{pathname: "/"}}>LOGOUT</Link></button>

</div>




</div>
);
}

错误:无法读取推送未定义的属性

最佳答案

使用 react 原理,您应该让 UserHome 拥有全局状态并将其传递给其子组件(其他 3 个组件)。另外,当 SearchFlight 有提交返回时,UserHome 应该将一个函数传递给 SearchFlight

此函数将更新 UserHome 的状态,并允许其子级拥有更新的数据。

示例:

class UserHome extends Component {
state = {
events: []
}

addEvent = newEvent => this.setState(state => {
const {events} = this.state
return [...events, newEvent]
})

render() {
const {events} = this.state
return (
<>
<SearchFlight events={events} addEvent={this.addEvent} />
<Events events={events} />
<Alerts events={events} />
</>
)
}
}


class SearchFlight extends Component {
handleSubmit = () => {
const {addEvent} = this.props

// create a new event here
// const myNewEvent = {...}

addEvent(myNewEvent)
}
render() {
const {events} = this.props
return (
<button onClick={this.handleSubmit} />
)
}
}

关于javascript - 在 Reactjs 中动态显示从一种状态到另一种状态的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53536858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com