gpt4 book ai didi

javascript - "Can only update a mounted or mounting component "componentDidMount 中的警告

转载 作者:行者123 更新时间:2023-12-01 02:39:02 26 4
gpt4 key购买 nike

理论上,我应该能够异步获取一些数据并更新 componentDidMount 内的组件。这是我的组件:

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

class App extends Component {
constructor () {
super()
this.state = {}
}

componentDidMount () {
fetch('/api/sessions')
.then(response => response.json())
.then(data => {
this.setState({ sessions: data.body })
})
}

render () {
return (
<div>
<h1>Sessions</h1>
<ul>
{this.state.sessions && this.state.sessions.map(session => {
return <li key={`session-${session._id}`}>{session._id}</li>
})}
</ul>
</div>
)
}
}

ReactDOM.render(<App />, document.querySelector('#root'))

组件渲染,并在收到数据时重新渲染。但我收到警告:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the App component.

我是否应该能够假设 componentDidMount 暗示实际安装的组件?我在这里做错了什么?

最佳答案

为了防止这种情况,您可以维护一个状态,例如 isMounted 并在 componentWillMount 和 componentWillUnmount 上更新它。每当您尝试异步设置状态时,首先检查组件是否仍然已安装。

componentWillMount = () => {
this.setState({
isMounted: true
})
}

componentWillUnmount = () => {
this.setState({
isMounted: false
})
}

componentDidMount () {
fetch('/api/sessions')
.then(response => response.json())
.then(data => {
if (this.state.isMounted) {
this.setState({ sessions: data.body })
}
})
}

关于javascript - "Can only update a mounted or mounting component "componentDidMount 中的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47690165/

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