简体   繁体   English

警告:无法在没有 useEffect 的情况下对未安装的组件执行 React state 更新

[英]Warning: Can't perform a React state update on an unmounted component without useEffect

Hello guys I have a basic component that takes product info and render it.大家好,我有一个获取产品信息并渲染它的基本组件。 It has a method called onAaddToWishList which takes product id, fetches the data from API and adds it to my wishlist.它有一个名为onAaddToWishList的方法,它获取产品 ID,从 API 获取数据并将其添加到我的愿望清单中。

const Product = (props) => {
    const [loading, setLoading] = useState(false);

    const onAddToWishlist = (e, id) => {
        e.preventDefault();

        if (!loading) {
            setLoading(true)

            instance.get(`/products/product/${id}`, {
                headers: {
                    'X-Auth-Token': findToken()
                }
            })
                .then(response => {
                    if (response.data.food) {
                        alert('Product added')

                        props.addToWishlist(response.data.food);

                        console.log(response.data.food)
                    }
                    else {
                        alert('Product not found')
                    }

                    setLoading(false);
                })
                .catch(err => {
                    console.log(err)

                    setLoading(false);

                    alert('Error occured.try again')
                })
        }
    }

    return (
        <div className="ProductCard">
            <div className="ProductCard--Image">
                <img src={props.image} alt="iclereu" />
            </div>
            <div className="ProductCard--Container">
                <h1>{props.title}</h1>
                <p>{props.description}</p>
                <span>&#8380; {props.price}</span>
                <div className="ProductCard--Nav">
                    <div className="ProductCard--Link">
                        <Link to="/">View more</Link>
                    </div>
                    <div className="ProductCard--Link">
                        <a
                            onClick={(e) => onAddToWishlist(e, props.id)}
                            href="#"
                        >
                            {!loading ? "+Wishlist" : "Loading..."}
                        </a>
                    </div>
                </div>
            </div>
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        wishlist: state.wishlist
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        addToWishlist: (product) => dispatch(wishlistActions.addToWishList(product))
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(Product)

This is my addToWishList action:这是我的addToWishList操作:

const addToWishList = (product) => {
    return dispatch => {
        let wishlist = [...store.getState().wishlist];
        let exists = wishlist.find(prod => prod.product._id === product._id);

        if (!exists) {
            wishlist = [...wishlist, {
                product: product,
                count: 1
            }]
        }
        else {
            let index = wishlist.findIndex(prod => prod.product._id === product._id);
            wishlist[index].count++;
        }

        dispatch({ type: "ADD_TO_WISHLIST", wishlist: wishlist })
    }
}

props.addToWishlist is function for redux action(it saves data to redux store( wishlist )). props.addToWishlist是 function 用于redux操作(它将数据保存到 redux 商店( wishlist ))。 Problem is whatever I do inside this action I get the following warning:问题是我在此操作中执行的任何操作都会收到以下警告:

Warning: Can't perform a React state update on an unmounted component.警告:无法对未安装的组件执行 React state 更新。 This is a no-op, but it indicates a memory leak in your application.这是一个无操作,但它表明您的应用程序中存在 memory 泄漏。 To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.要修复此问题,请在 useEffect 清理 function 中取消所有订阅和异步任务。

But I don't use useEffect hook.但我不使用useEffect钩子。 It works actually(it adds a product to wishlist ) but the warning is pretty annoying like I do something wrong.它实际上有效(它向wishlist添加了一个产品)但警告很烦人,就像我做错了什么一样。 Even I console the argument of the redux action it gives the same error.即使我控制台 redux 操作的论点它给出了相同的错误。 I would be grateful if someone helps me如果有人帮助我,我将不胜感激

The reason is that props of your component are changing (wishlist) component is rerendering and in this time setLoading is trying to update the state of the unmounted component.原因是您的组件的道具正在更改(愿望清单)组件正在重新渲染,此时setLoading正在尝试更新已卸载组件的 state。 For this example, useEffect is not really useful.对于这个例子,useEffect 并不是很有用。 The quickest solution is to keep the loading state in redux store as well and remove const [loading, setLoading] = useState(false);最快的解决方案是在 redux 存储中保持加载 state 并删除const [loading, setLoading] = useState(false); from this component.从这个组件。 Also, it worth mentioning, that it's better to decompose presentation and API interaction.另外,值得一提的是,最好分解演示文稿和 API 交互。 I can recommend you two simple approaches for redux: https://www.npmjs.com/package/redux-api-middleware and https://www.npmjs.com/package/redux-thunk我可以向您推荐 redux 的两种简单方法: https://www.npmjs.com/package/redux-api-middlewareZ5E056C500A1C4B6A7110B50D807BADEred5Z-thun.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 useEffect 挂钩对未安装的组件执行 React state 更新 - Can't perform a React state update on an unmounted component with useEffect hook 无法使用 useEffect 对未安装的组件问题执行反应状态更新 - can't perform a react state update on an unmounted component issue with useEffect 警告:无法对未安装的组件执行 React state 更新。 使用效果清理 function - Warning: Can't perform a React state update on an unmounted component. useEffect cleanup function React:“无法在未安装的组件上执行 React 状态更新”没有 useEffect 函数 - React: "Can't perform a React state update on an unmounted component" without useEffect function 无法对卸载的组件警告执行React状态更新 - Can't perform a React state update on an unmounted component warning 警告:无法对未安装的组件执行 React state 更新 - Warning: Can't perform a React state update on an unmounted component React useEffect 导致:无法对未安装的组件执行 React 状态更新 - React useEffect causing: Can't perform a React state update on an unmounted component 无法对未安装的组件执行 React state 更新。 使用效果 React-Native - Can't perform a React state update on an unmounted component. useEffect React-Native 在useEffect清理函数执行之前获取“无法对卸载的组件执行React状态更新” - Getting 'Can't perform a React state update on an unmounted component' before useEffect cleanup function executes Next.js 仅在桌面上渲染视频:useEffect 无法对未安装的组件执行 React state 更新 - Next.js render video only on desktop: useEffect can't perform a React state update on an unmounted component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM