javascript - React componentWillReceiveProps 不更新状态

标签 javascript reactjs lifecycle

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

是我对 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;

最佳答案

您正在复制数据,并给自己带来不必要的麻烦。

selectedSubselectedStop 都被存储为 propsstate 属性。您需要决定这些数据的存放位置并将其放在一个单独的位置。

您遇到的问题完全围绕着您正在更改 state 属性并期望这会触发对 Prop 的更改这一事实。仅仅因为它们共享一个名称并不意味着它们具有相同的值。

关于javascript - React componentWillReceiveProps 不更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46162505/

相关文章:

entity-framework - 如何在 CRUD 场景中跟踪从 ObservableCollection 中删除的对象?

javascript - 使用 Javascript D3 库,如何在 mousemove 事件中确定鼠标在区域元素数据集中的位置?

javascript - 返回非值属性

javascript - React js访问另一个类的状态

html - 在 React 中 dangerouslySetInnerHTML 不适用于 html 标签。

ios - 应用委托(delegate)中 performFetchWithCompletionHandler 的用途是什么?

javascript - 使用 .each 在 .resize 上执行函数数组

javascript - 将父 div 扩展到 TALLEST 绝对定位子项的高度

javascript - React material-ui 文本字段屏幕抖动

javascript - 为什么 ngOnChanges() 在 @Input() 更新数据 Angular 8 时不会触发?