如何在 React 中使用 getDerivedStateFromProps 而不是 componentWillReceiveProps
how to use getDerivedStateFromProps instead of componentWillReceiveProps in React
我想更新我的代码以使用 getDerivedStateFromProps 而不是 componentWillReceiveProps,因为我收到了已弃用的错误。该组件正在接收一个日期道具,每次更改日期时都需要 运行 带有新日期的 getList。为此,我使用下面的代码
componentWillReceiveProps(nextProps) {
const {date} = this.props;
if (nextProps.date !== date) {
console.log('prop changed to : ', nextProps.date);
this.getList(nextProps.date);
}
}
我尝试了以下但它不起作用
static getDerivedStateFromProps(props, state) {
const {date} = this.props;
if (props.date !== date) {
console.log('prop changed to : ', props.date);
this.getList(props.date);
}
return;
}
getDerivedStateFromProps
看起来不像是您要执行的操作的正确工具。而是使用 componentDidUpdate
:
componentDidUpdate(prevProps) {
const { date } = this.props;
if (prevProps.date !== date) {
this.getList(date);
}
}
很少使用getDerivedStateFromProps
。有关何时使用 getDerivedStateFromProps
的更多信息,我推荐 this article
我想更新我的代码以使用 getDerivedStateFromProps 而不是 componentWillReceiveProps,因为我收到了已弃用的错误。该组件正在接收一个日期道具,每次更改日期时都需要 运行 带有新日期的 getList。为此,我使用下面的代码
componentWillReceiveProps(nextProps) {
const {date} = this.props;
if (nextProps.date !== date) {
console.log('prop changed to : ', nextProps.date);
this.getList(nextProps.date);
}
}
我尝试了以下但它不起作用
static getDerivedStateFromProps(props, state) {
const {date} = this.props;
if (props.date !== date) {
console.log('prop changed to : ', props.date);
this.getList(props.date);
}
return;
}
getDerivedStateFromProps
看起来不像是您要执行的操作的正确工具。而是使用 componentDidUpdate
:
componentDidUpdate(prevProps) {
const { date } = this.props;
if (prevProps.date !== date) {
this.getList(date);
}
}
很少使用getDerivedStateFromProps
。有关何时使用 getDerivedStateFromProps
的更多信息,我推荐 this article