gpt4 book ai didi

javascript - 使用相同的 react 组件进行添加和编辑

转载 作者:行者123 更新时间:2023-12-02 23:19:13 24 4
gpt4 key购买 nike

我想使用相同的模式对话框进行编辑和添加。我之前使用 componentWillReceiveProps 并使用 props 设置新状态。但是我读到它已被弃用。我尝试使用 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
});
}
}

使用上面的代码,每当 Prop 发生变化时,我都会用新状态重置模式窗口。相同的代码不适用于 getDerivedStateFromProps 我唯一的解决方案是将 keyString(new Date().getTime()) 添加到我的模态组件,以便每次我打开模态时,它都会重置其状态。

我的问题是;

  • 如果我使用 "react": "16.8.3"和 "react-native": "0.59.9",我应该继续使用 componentWillReceiveProps 吗?
  • 可以使用按键重置我的模式吗?如果不是,有什么更好的方法来重置它以进行添加/编辑?

最佳答案

从长远来看,我认为继续使用即将弃用的方法将符合您的最佳利益。您可以使用 componentDidUpdate() 来复制相同的行为,它捕获 prevProps,您可以用它来与新的 props 进行比较。

  componentDidUpdate(prevProps) {
if (prevProps.original !== this.props.original) { //update state if different
const item = this.props.original;
this.setState({
name: item.name,
slug: item.slug
});
} else {
this.setState({ // Fresh
name: null,
slug: null
});
}
}

这里还有一个沙箱,可供引用如何从模式内部创建编辑功能:https://codesandbox.io/s/awesome-maxwell-qh76t

关于javascript - 使用相同的 react 组件进行添加和编辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57023390/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com