如何正确更新组件?(反应+通量)

时间:2017-06-15 08:50:34

标签: reactjs flux reactjs-flux

我正在使用ReactJs + flux。在我的商店中,我有一个方法 - getCurrentEvents(key)。它接收键并正确创建对象数组。之后它会发出变化。 我有组件列表,它有处理程序。此处理程序回答商店更改并调用方法displayEvents()。此方法更新组件的状态。这个概念有效,但不正确。当我致电getCurrentEvents(key)时,它会开始更新EventList-component并且不会停止,因为浏览器中的结果标签会冻结。据我了解,我得到的内容就像无限制的更新周期一样,我认为错误的是在组件的方法中,但我无法理解错误在哪里。如何解决这个错误?

商店代码:

class EventStore extends EventEmitter {
  constructor() {
    super();
    this.events = [{
        id: 1,
        title: 'title 1',
        date: '2017-04-11 09:14:01'
        }, {
        id: 2,
        title: 'title 2',
        date: '2017-04-11 09:24:01'
        }, {
        id: 3,
        title: 'title 3',
        date: '2017-04-12 09:14:01'
        }, {
        id: 4,
        title: 'title 4',
        date: '2017-11-12 19:14:01'
        }, {
        id: 5,
        title: 'title 5',
        date: '2017-06-13 19:00:01'
        }
    ];
  }

  getCurrentEvents(key) {
    var currentEvents = [];
    for (event in this.events){
        if (this.events[event].date.includes(key)) {
            currentEvents.push(this.events[event]);
        }
    }

    return currentEvents;
    this.emit("change");
  }

  createEvent(new_event) {
    this.events.push ({
        title: new_event.title,
        date: new_event.date
    })
    this.emit("change");
  }

  getAll() {
    return this.events
  }


  handleActions(action) {
    switch(action.type) {
        case 'CREATE_EVENT' : {
        this.createEvent(action.new_event);
      }
        case 'DISPLAY_CURRENT_EVENTS' : {
        this.getCurrentEvents(action.key);
      }
    }
  }
}

const eventStore = new EventStore;

dispatcher.register(eventStore.handleActions.bind(eventStore))

export default eventStore;

EventList组件代码:

export default class EventList extends React.Component {

      constructor () {
        super();
        this.state = {
            events: EventStore.getCurrentEvents()
        };
        this.displayEvents = this.displayEvents.bind(this);
      }

      componentWillMount() {
        EventStore.on("change", this.displayEvents)
      }

      displayEvents() {

        this.setState ({
                events: EventStore.getCurrentEvents()
        })
      }

      render() {
        console.log('form events LIST', this.state)

        const events = this.state.events ;
        var EventsList = [];

        for (event in events) {
            EventsList.push(
             <li key={events[event].id} id={events[event].id}>
                {events[event].title} , {events[event].date}
             </li>
             )
        }
        return (
        <div className="">
          <h3> Events on this day </h3>

          <ul className="event-list-wrapper">
             {EventsList}
          </ul>
        </div>
        );
      }
 }

1 个答案:

答案 0 :(得分:1)

看起来是因为getCurrentEvents(key)功能正在发出变化&#39;这会触发displayEvents ...调用getCurrentEvents(key) ...会发出更改&#39;调用displayEvents ...

的事件