gpt4 book ai didi

javascript - 从 Reactjs 中的另一个组件更新状态

转载 作者:行者123 更新时间:2023-11-30 14:16:09 25 4
gpt4 key购买 nike

我想从“A”组件更新主组件的状态,然后将其推送到“B”组件,然后使用它渲染以动态填充框。

主要组件:

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

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

addAlert = newAlert => this.setState(state =>{
const {alerts} = this.state
return [...alerts, newAlert]
});

render(){
const {events} = this.state
const {alerts} = this.state
console.log(events) // events are empty even after I pass and store it
// in SearchFlight Component
return(
<div >

<SearchFlight events={events} alerts={alerts} addAlert={this.addAlert} addEvent={this.addEvent} />
<Events events={events}/>
<Alerts />
</div>

);

}

SearchFlight 组件(一个组件):

handleSubmit= event =>{
const {addEvent} = this.props
const {addAlert} = this.props
event.preventDefault();

var newEvents=[];
var newAlerts=[];


var singleEvent={
event_name:'home',
date_time:'12-08-18 12:45 AM',
};

newEvents.push(singleEvent);

newAlerts.push("Remove the luggage tag");

addAlert(newAlerts);
addEvent(newEvents);

}

然后我有 Event Component(B Component),它现在只有 render 方法。我想在这里获取更新的事件。

问题:当我在 Main Component

的渲染方法中执行 console.log(events) 时获取空事件

最佳答案

您没有在 addEventsaddAlerts 方法中正确使用 setState。 setState的回调模式需要返回一个对象

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

addAlert = newAlert => this.setState(state =>{
const {alerts} = state
return {alerts: [...alerts, ...newAlert]
});

此外,由于事件是一个对象数组,您需要迭代它们才能呈现。引用How to render an array of objects in React?回答有关如何执行此操作的更多详细信息

关于javascript - 从 Reactjs 中的另一个组件更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53552325/

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