React componentWillReceiveProps不更新状态

时间:2017-09-11 18:48:53

标签: javascript reactjs lifecycle

我在这里有这个React父组件。此时的子组件只是返回下拉菜单。我期望componentWillReceiveProps会在这里更新状态,而状态又应该作为props传递给StopList。但是,当通过handleSubSelect更改state.selectedSub时,没有任何反应,StopList也不会收到任何道具。

我的错误是componentWillReceiveProps的异步性质吗?它在我的代码中是错误的地方吗?我使用了错误的生命周期方法吗?

// We're controlling all of our state here and using children
// components only to return lists and handle AJAX calls.

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

class SubCheck extends Component {

  constructor (props) {
    super(props);
    this.state = {
        selectedSub: '--',
        selectedStop: null,
        stops: ['--'],
    };
    this.handleSubSelect.bind(this);
    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.
    componentWillReceiveProps(nextProps) {
        var stopData = require('../utils/stops');
        var stopsArray = [];
        var newSub = nextProps.selectedSub
        for(var i = 0; i < stopData.length; i++) {
            var stop = stopData[i];

            if (stop.stop_id.charAt(0) === this.state.selectedSub) {
                stopsArray.push(stop.stop_name);
            }
        }
        if (stopsArray.length !== 0 && newSub !== this.state.selectedSub) {
            this.setState({stops: stopsArray});
        }
    }

    handleSubSelect(event) {
        this.setState({selectedSub:event.target.selectedSub});
    }

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

    render() {
        return (
            <div>
                <SubList onSubSelect={this.handleSubSelect.bind(this)}/>
                <StopList stops={this.state.stops} onStopSelect={this.handleStopSelect.bind(this)}/>
            </div>
        );
    }
}

export default SubCheck;

1 个答案:

答案 0 :(得分:2)

您正在复制数据,并导致您自己头疼,这是不必要的。

selectedSubselectedStop都存储为propsstate属性。您需要确定此数据的存在位置并将其放在一个单一的位置。

您遇到的问题完全围绕着这样一个事实:您正在更改state属性并希望这会触发对道具的更改。仅仅因为他们共享一个名字并不意味着他们是相同的价值。

相关问题