![](/img/trans.png)
[英]Updating redux state doesn't call componentWillReceiveProps
[英]React componentWillReceiveProps not updating state
我在這里有這個React父組件。 此時的子組件只是返回下拉菜單。 我希望componentWillReceiveProps將在這里更新狀態,而狀態又應作為道具傳遞給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;
您正在復制數據,並導致不必要的頭痛。
selectedSub
和selectedStop
都存儲為props
和state
屬性。 您需要確定這些數據的存放位置,並將其放置在單個位置。
您所遇到的問題完全圍繞着以下事實:您正在更改state
屬性,並期望這會觸發對道具的更改。 僅僅因為它們共享一個名稱並不意味着它們具有相同的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.