【发布时间】:2020-06-08 02:46:14
【问题描述】:
我有Dropdown comp,用户可以在其中选择一些过滤器。
我也有按钮clear-filters,当用户单击该按钮时,父组件中的过滤器消失了,但在dropdown comp 中仍然保持选中的过滤器。
这意味着我的下拉列表没有像以前那样正确更新UNSAFE_componentWillReceiveProps:
带有UNSAFE_componentWillReceiveProps()的下拉组件:
state = {
options: props.options || []
};
componentDidMount() {
this.setSelectedOptions(this.props);
document.addEventListener('mousedown', (e) => this.handleClickOutside(e));
if (this.props.onRef) {
this.props.onRef(this);
}
}
UNSAFE_componentWillReceiveProps(props) {
this.setSelectedOptions(props);
}
这是 Dropdown 迁移版本,它不像以前那样工作:
state = {
options: props.options || []
};
componentDidMount() {
this.setSelectedOptions(this.props);
document.addEventListener('mousedown', (e) => this.handleClickOutside(e));
if (this.props.onRef) {
this.props.onRef(this);
}
}
static getDerivedStateFromProps(nextProps, prevState) {
const { options } = nextProps;
// CHECKING DOES SOME OPTIONS PROPERTIES ARE CHANGED OR NOT
options.forEach((filter, i) => {
if (filter.selected !== prevState.options[i].selected) {
return { options };
}
});
return null;
}
有什么建议吗?
【问题讨论】:
标签: javascript reactjs typescript next.js