理论上,我应该能够异步获取一些数据并在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
暗示组件实际安装了吗?我在这里做错了什么?
答案 0 :(得分:2)
要防止它您可以维护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 })
}
})
}