componentDidMount() 如何做一个 setState()



我正在尝试迁移到 React 17,我想改变

componentWillMount () {
this.setState({ model: this.props.formModel })
}

到 React 17

componentDidMount () {
this.setState({ model: this.props.formModel })
}

但是我在componentDidMount中有这个错误

不要在组件DidMount中使用setState

有什么建议吗?

我认为这个警告来自ESLint。这是在组件中调用setState时实施的规则DidMount导致可见的渲染闪烁。情况不再如此,因此您可以禁用该规则。

但是,如果您正在设置初始状态,这应该发生在您的构造器中。看这里:

https://reactjs.org/docs/react-component.html#componentdidmount

您可以立即在 componentDidMount(( 中调用 setState((。它将触发额外的渲染,但它将在浏览器更新屏幕之前发生。这保证了即使在这种情况下 render(( 将被调用两次,用户也不会看到中间状态。请谨慎使用此模式,因为它通常会导致性能问题。在大多数情况下,您应该能够在 constructor(( 中分配初始状态。但是,对于模态和工具提示等情况,当您需要在渲染取决于其大小或位置的内容之前测量 DOM 节点时,这可能是必要的。

我们已经必须明白它两者之间的区别:componentWillMount 和 componentDidMount

componentWillMount is called before the render and
componentDidMount is much more used to update the dom
componentDidMount is the perfect place to make your setState()
you will rarely need to use componentWillMount for this kind of action.

也许您可以展示更多代码,以便我们了解您出现此错误的原因:

不要在组件DidMount中使用setState

这可能是因为你的林特,正如克里斯蒂安所说

关于为什么你不应该在 componentDidMount 中调用 setState,你可以看看 React 文档

您可以立即在 componentDidMount(( 中调用 setState((。它将触发额外的渲染,但它将在浏览器更新屏幕之前发生。这保证了即使在这种情况下 render(( 将被调用两次,用户也不会看到中间状态。请谨慎使用此模式,因为它通常会导致性能问题。在大多数情况下,您应该能够在 constructor(( 中分配初始状态。但是,对于模态和工具提示等情况,当您需要在渲染取决于其大小或位置的内容之前测量 DOM 节点时,这可能是必要的。

你可以像这样从构造函数中的 props 设置状态:

class ReactComp(Component):
constructor(props) {
super(props);
this.state = {
model: props.formModel
}
}

但是这将在 React 第一次为您挂载此组件时起作用。当数据更改时,状态不会反映。所以我指的是使用getDerivedStateFromProps,这也是一种推荐的实现方式,因为组件WillMount将在几个版本中被弃用。

class ReactComp(Component):
constructor(props) {
super(props);
}
static getDerivedStateFromProps(props, state) {
if (props.formModel !== state.formModel) {
return {
formModel: props.formModel,
};
}
// Return null to indicate no change to state.
return null;
}

希望对您有所帮助!

你不使用componentDidMount().您可以使用componentDidUpdate().

componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.state.model !== prevProps.formModel) {
this.state({ model : prevProps.formModel})
}
}

只是你必须使用

state = ({ model: this.props.formModel })

不需要打电话componentDidMount

最新更新