如何在FC中使用useEffect制作getDerivedStateFromProps?

问题描述 投票:0回答:1

我有一个旧的React组件(它是类),现在我正在尝试将它重写为FC。 有一些类方法,如构造函数、ComponentDidMount、ComponentWillUnmount 等。 我在尝试重写方法 getDerivedStateFromProps 时遇到了一些困难。这是它的样子:

static getDerivedStateFromProps(props: CourseProps, state: State): State | null {
    const {
        courseId,
    slideInfo,
    units,
    enterToCourse,
    courseInfo
    } = props;

    if (!units) {
        return null;
    }

    const slideId = slideInfo.slideId;

    if (state.currentCourseId !== courseId ||
    state.currentSlideId !== slideId ||
    slideInfo.slideType !== state.currentSlideType) {
    enterToCourse(courseId);
    const openUnitId = findUnitIdBySlideId(slideId, courseInfo);
    const openedUnit = openUnitId ? units[openUnitId] : undefined;
    window.scrollTo(0, 0);
    const Page = WebEditor2.getOpenedPage(props.courseInfo, slideInfo?.slideType);
    const title = WebEditor2.getTitle(slideInfo.navigationInfo?.current.title);

    return {
        Page,
        title,
        currentSlideId: slideId,
        currentCourseId: courseId,
        currentSlideType: slideInfo.slideType,
        highlightedUnit: openUnitId || null,
        openedUnit,
    };
    }

    return null;
}

我做了这样的东西:

useEffect(() => {
    const { courseId, slideInfo, units, enterToCourse, courseInfo } = props;

    if (!units) {
        return;
    }

    const slideId = slideInfo.slideId;

    if (state.currentCourseId !== courseId ||
        state.currentSlideId !== slideId ||
        slideInfo.slideType !== state.currentSlideType) {
        enterToCourse(courseId);
        const openUnitId = findUnitIdBySlideId(slideId, courseInfo);
        const openedUnit = openUnitId ? units[openUnitId] : undefined;
        window.scrollTo(0, 0);
        const Page = getOpenedPage(props.courseInfo, slideInfo?.slideType);
        const title = getTitle(slideInfo.navigationInfo?.current.title);

    setState( {
        Page,
        title,
        currentSlideId: slideId,
        currentCourseId: courseId,
        currentSlideType: slideInfo.slideType,
        highlightedUnit: openUnitId || null,
        openedUnit,
    });
    }
}, [props.courseId, props.slideInfo, props.units, props.enterToCourse, props.courseInfo]);

但现在我总是出现错误:超出最大更新深度。当组件在 componentWillUpdate 或 componentDidUpdate 中重复调用 setState 时,可能会发生这种情况。 React 限制嵌套更新的数量以防止无限循环。

我应该如何重写这个方法?任何帮助表示赞赏。

reactjs react-native react-hooks react-redux
1个回答
0
投票

首先你好,我的回答可能不够充分,因为我看不到你的全部代码,但是你在类结构中使用的状态逻辑在功能使用中变成了useState。如果你的用法是useState,你应该知道useEffect是每次状态更新时都会自动触发,因此最好保持不变。

© www.soinside.com 2019 - 2024. All rights reserved.