如何在父组件中使用多个事件处理程序正确更新状态(React)

时间:2017-11-19 22:37:17

标签: javascript reactjs

我在一个父组件中拥有应用程序的所有状态。它呈现多个子组件,其中两个包含下拉菜单。父组件具有用于这两个下拉菜单组件的事件处理程序,这些组件应该更新状态。第一个处理程序正确更新状态,但第二个处理程序没有。我假设这与setState()异步有关,但我不确定。有什么办法解决这个问题?第二个处理程序应该是生命周期事件的一部分吗?还有别的吗?

代码:

import React, { Component } from 'react';
import SubList from './SubList';
import StopList from './StopList';
import { IsDelayN, IsDelayS } from './IsDelay';

class SubCheck extends Component {

  constructor (props) {
    super(props);
    this.state = {
        selectedSub: null,
        selectedStop: null,
        stops: [],
    };
    this.handleSubSelect = this.handleSubSelect.bind(this);
    this.handleStopSelect = this.handleStopSelect.bind(this);
    }

    // We want the user to be able to select their specific subway
    // stop, so obviously a different array of stops needs to be 
    // loaded for each subway. We're getting those from utils/stops.json.
    handleSubSelect(event) {
        var stopData = require('../utils/stops');
        var stopsArray = [];
        var sub = event.target.value
        for (var i = 0; i < stopData.length; i++) {
            var stop = stopData[i];

            if (String(stop.stop_id).charAt(0) === sub) {
                stopsArray.push(stop.stop_name);
            }
        }
        this.setState(() => {
            return {
                selectedSub: sub,
                stops: stopsArray
            }
        });
    }

    handleStopSelect(event) {
        this.setState({selectedStop: event.target.value});
    }

    render() {
        return (
            <div>
                <SubList onSubSelect={this.handleSubSelect}/>
                <StopList stops={this.state.stops} onStopSelect={this.handleStopSelect}/>
                <IsDelayN sub={this.state.selectedSub} stop={this.state.selectedStop}/>
                <IsDelayS sub={this.state.selectedSub} stop={this.state.selectedStop}/>
            </div>
        );
    }
}

export default SubCheck;

0 个答案:

没有答案