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'.,一般是循環(huán)的時候沒有加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操作。當你切換路由時,組件已經(jīng)被卸載(unmounted)了,此時異步操作中callback還在執(zhí)行,因此setState沒有得到值。不能在組件銷毀后設置state,防止出現(xiàn)內(nèi)存泄漏的情況。
(1)在卸載的時候?qū)λ械牟僮鬟M行清除(例如: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;
};
}