问题描述
我目前使用的是 React 16.3(React Native),写成 此处,它表明我应该在 componentDidMount 而不是 componentWillMount 内发出任何异步请求,因为这将很快被弃用.
不幸的是,当我尝试在 componentDidMount 中获取数据时,我收到了一个无操作警告,将从我的 axios 请求返回的数据设置为我的状态.
这是一个片段——
导出默认类 MyComponent extends Component {状态 = {我的数据:[]}componentDidMount() {axios.get('api-endpoint').then(res => this.setState({ myData: res.data })}render() { return }}
和警告——
警告:只能更新已安装或正在安装的组件.这通常意味着您调用了 setState、replaceState 或forceUpdate 在卸载的组件上.这是一个无操作.请检查 MyComponent 组件的代码.
这就是组件中存在异步代码的问题.例如,当 Promise 解析时(可能需要几秒钟),用户可能已经导航到应用程序的另一部分,因此当 Promise 解析并尝试执行 setState
时 - 您会收到您尝试执行的错误更新卸载的组件.
我的建议是使用诸如 redux-thunk、redux-saga 或 redux-observable 之类的东西作为您的异步逻辑......但是,您可以做一个简单的检查 - 但它是一个反模式 :
导出默认类 MyComponent extends Component {状态 = {我的数据:[]}componentDidMount() {this.isMounted = true;axios.get('api-endpoint').then(res => {如果(this.isMounted){this.setState({ myData: res.data })}})}componentWillUnmount() {this.isMounted = false;}render() { return ...}}
I'm currently using React 16.3(React Native), written here, it suggests that I SHOULD be making any async requests inside of componentDidMount instead of componentWillMount because that will soon be deprecated.
Unfortunately I'm getting a no-op warning as I'm trying to fetch data inside of componentDidMount, setting the data returned from my axios request as my state.
Here's a snippet —
export default class MyComponent extends Component {
state = {
myData: []
}
componentDidMount() {
axios.get('api-endpoint')
.then(res => this.setState({ myData: res.data })
}
render() { return <View>...</View> }
}
and the warning —
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 MyComponent component.
That's the problem of having asynchronous code in your components. When for example Promise resolves (might take few seconds), a user may have already navigated to another part of your application, so when Promise resolves and tries to execute setState
- you get the error that you try to update unmounted component.
My suggestion is to use something like redux-thunk, redux-saga or redux-observable etc. for your asynchronous logic... However, you can do a simple check - but it is an antipattern :
export default class MyComponent extends Component {
state = {
myData: []
}
componentDidMount() {
this.isMounted = true;
axios.get('api-endpoint')
.then(res => {
if(this.isMounted) {
this.setState({ myData: res.data })
}
})
}
componentWillUnmount() {
this.isMounted = false;
}
render() { return <div>...</div> }
}
这篇关于在 componentDidMount 内的回调中设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!