【发布时间】:2019-07-13 22:56:55
【问题描述】:
我想使用相同的模式对话框进行编辑和添加。我以前使用componentWillReceiveProps 并使用道具设置新状态。但是我读到它已被弃用。我尝试使用getDerivedStateFromProps,但它的行为不同。
我的旧代码如下所示
componentWillReceiveProps(nextProps) {
if (nextProps.original) { // Are we editing?
const item = nextProps.original;
this.setState({
name: item.name,
slug: item.slug
});
} else {
this.setState({ // Fresh
name: null,
slug: null
});
}
}
使用上面的代码,每当道具改变时,我都会用新状态重置模态窗口。相同的代码不适用于getDerivedStateFromProps 我唯一的解决方案是将key 和String(new Date().getTime()) 添加到我的模态组件中,这样每次我打开模态时,它都会重置其状态。
我的问题是;
- 如果我将 "react": "16.8.3" 与 "react-native": "0.59.9" 一起使用,我应该继续使用
componentWillReceiveProps吗? - 可以使用按键重置我的模式吗?如果不是,有什么更好的方法来重置它以进行添加/编辑?
【问题讨论】:
标签: javascript reactjs