react 常見報錯

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;
    };
}

參考

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容