我正在开发一个简单的网站使用React + nextJS。
为了保持简单,假设我有两次跌落。
Dropdown A (country)
- Dropdown B (run time options based on the country selection)
下拉列表A在主页上。下拉列表B是一个独立的组件,我设计了我的组件,如下所示。
class MySubComponent extents Component{
state = {
options: []
}
static async getDerivedStateFromProps(props){
let options = await axios(....);
console.log(options)
return {options};
}
render(){
<div>
{this.state.options}
</div>
}
}
主页包括主页上的MySubComponent
。
<MySubComponent loadOptionBfor={dropdownAvalue} />
下拉列表A的OnChange事件应该重新加载下拉列表B。我看到了控制台日志语句,其中显示了B get选项。但是,在ajax请求完成之前,MySubComponent
将在没有任何选项的情况下呈现。
怎么解决这个问题?
发布于 2018-11-07 07:46:23
"should return an object to update the state, or null to update nothing",它只能同步地做到这一点。
我认为您最好将当前的道具和componentDidUpdate
中以前的道具进行比较,如果您想要比较更改的道具,可以获得您的新选项。
示例
class MySubComponent extends Component {
state = {
options: []
};
async componentDidUpdate(prevProps) {
if (prevProps.country !== this.props.country) {
let response = await axios(/* ... */);
this.setState({ options: response.data });
}
}
render() {
return (
<select>
{this.state.options.map(option => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
);
}
}
https://stackoverflow.com/questions/53192350
复制相似问题