簡體   English   中英

從React.js中的另一個組件更新狀態

[英]Updating state from another component in Reactjs

我想從“ 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 Component(一個組件):

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方法。 我想在這里獲取更新的事件。

問題 :在主組件的 render方法中執行console.log(events)時獲取空事件

國家對組成部分是私有的。 如果使用prop將狀態傳遞給子組件,則應再次按照reactjs指南對prop進行更改。

您只能從道具中讀取組件A中的值,然后修改該值以將其進一步傳遞給嵌套的組件。 但是不能從A修改主要組件的狀態。

檢查一下: https : //reactjs.org/docs/state-and-lifecycle.html

您沒有在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]
  });

同樣,由於事件是對象的數組,因此您需要對其進行迭代以進行渲染。 請參閱如何在React中渲染對象數組? 回答有關如何執行此操作的更多詳細信息

正如OneJeet指出的那樣,React完全是自頂向下的方法,子組件應該不知道父組件是無狀態還是有狀態的。

將setState作為函數傳遞並允許子組件調用它是不好的做法。 一種方法是使用redux,而無需從子組件更新父狀態或以其他方式重新構建整個事物。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM