【发布时间】:2019-03-27 20:51:44
【问题描述】:
想象一个带有<select> 元素的简单 React 组件,它允许根据国家/地区选择城市。例如
<MyCitySelectComponent
country={ 'France' }
city={ 'Paris' }
onChange={ someFunction }
/>
- 安装后,它应加载可用城市列表(基于国家/地区)并呈现
<select>。 - 当 city 属性改变时 - 它应该修改
<select>输入值并触发 onChange 事件。 - 当 country 属性发生更改(从父组件) - 它应该从远程服务器重新加载可用城市列表并触发相同的 onChange 事件。
我设法实现了前两个,这里是简化的代码:
class MyCitySelectComponent extends Component {
constructor(props) {
super(...props);
this.state = {
cities: null,
city: props.city,
country: props.country
};
}
onCityChange( e ) {
this.setState({
city: e.target.value
});
this.props.onChange( e.target.value );
}
loadCities() {
fetch({
path: '/get/cities?country=' + this.state.country,
}).then( cities => {
this.setState({
cities: cities
});
});
}
componentDidMount() {
this.loadCities();
}
render() {
if ( !this.state.cities ) {
// not loaded yet
return null;
}
return (
<select>
{ this.state.cities.map( ( name, index ) =>
<option
value={ name }
onChange={ this.onCityChange }
selected={ name === this.state.city }
/>
) }
</select>
)
}
}
但是当从父组件动态更改国家/地区时,我无法重新加载城市。我尝试使用shouldComponentUpdate,但我得到的只是无限循环。
这种类型的组件有什么模式吗?
谢谢。
【问题讨论】:
-
这可能是你想要的getDerivedStateFromProps
标签: javascript reactjs ecmascript-6