1. 未加关键字 key
Warning: Each child in a list should have a unique "key" prop.
-
Check the render method of 'Body'.
,Table
组件没有加rowKey
导致的。
<Table dataSource={data} rowKey={(record) => record.id}>
// ...
</Table>
-
Check the render method of 'Cell'.
,一般是循环的时候没有加key
或者key
不存在导致的,key
要加在最外层。
return (
<ul>
{items.map((item: any) => (
<Tooltip title={item.name} key={item.id}>
<li>
{item.name || ''}
</li>
</Tooltip>
))}
</ul>
);
2. 在组件销毁后 setState
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
- react 在切换路由时报以上错误,实际的原因是因为在组件挂载(mounted)之后进行了异步操作,比如 ajax 请求或者设置了定时器等,而你在callback中进行了setState操作。当你切换路由时,组件已经被卸载(unmounted)了,此时异步操作中callback还在执行,因此setState没有得到值。不能在组件销毁后设置state,防止出现内存泄漏的情况。
(1)在卸载的时候对所有的操作进行清除(例如:abort你的ajax请求或者清除定时器)
componentDidMount = () => {
//1.ajax请求
$.ajax('你的请求',{})
.then(res => {
this.setState({
aa:true
})
})
.catch(err => {})
//2.定时器
timer = setTimeout(() => {
//dosomething
},1000)
}
componentWillUnMount = () => {
//1.ajax请求
$.ajax.abort()
//2.定时器
clearTimeout(timer)
}
(2)设置一个flag,当unmount的时候重置这个flag
componentDidMount = () => {
this._isMounted = true;
$.ajax('你的请求',{})
.then(res => {
if(this._isMounted){
this.setState({
aa:true
})
}
})
.catch(err => {})
}
componentWillUnMount = () => {
this._isMounted = false;
}
// hooks
function Example(props) {
const [loading, setLoading] = useState(true);
useEffect(() => {
let mounted = true;
fetchAPI.then(() => {
if (mounted) {
setLoading(false);
}
})
return function cleanup() {
mounted = false;
}
}, [])
return <div>...</div>
}
(3)最简单的方式(万金油)
componentDidMount = () => {
$.ajax('你的请求',{})
.then(res => {
this.setState({
data: datas,
});
})
.catch(error => {
});
}
componentWillUnmount = () => {
this.setState = (state,callback)=>{
return;
};
}