呈现不同的组件时(useState)无法更新组件

时间:2020-09-08 08:56:48

标签: javascript reactjs react-hooks

我正在尝试从子组件执行useState,但是触发了警告,因此我的状态没有更新。

错误:


Cannot update a component (`GetProduct`) while rendering a different component (`PageMenu`). To locate the bad setState() call inside `PageMenu`

我的setState组件中只有useState个钩子触发了一个GetProduct触发器。

GetProduct组件:


export const GetProduct: React.FC<Props> = () => {

    let data = RecovData()
    console.log(data.formationData)

    const groupedByCategories = lodash.groupBy(data.formationData,
        function (form) {
            return form.categorie;
        })

    const categories = Object.keys(groupedByCategories);

    console.log('0', categories.length)

    const [currentCategory, setCurrentCategory]: [null | string, Function] = useState(null)


    useEffect(() => {
        if (categories.length > 0) {
            setCurrentCategory(categories[0])
        }
    }, [categories])


    console.log('current', currentCategory)
    if (currentCategory != null) {
        return (
            <div>
                <PageMenu
                    categories={categories}
                    setCurrentCategory={setCurrentCategory}
                />
                <MainCard
                    currentCategory={currentCategory}
                    formationData={data.formationData}
                    catalog={data.catalog}
                    shopId={data.shopId}
                    viewer={data.viewer}
                />
            </div>
        );
    }
    return null
};

PageMenuuseState中使用:

interface Props {
    categories?: string[],
    setCurrentCategory?: Function,
}

export const PageMenu: React.FC<Props> = (props) => {

    const categories = props.categories;
    const setCategory = props.setCurrentCategory;

    return (

        <PageHeader
            className="product-page-header"
            title="Découvrir toutes nos formations"
        >
            <Menu className="page-menu_wrapper" mode="horizontal" defaultSelectedKeys={['0']}>
                {categories.map((categorie, index) => {
                    console.log('ici', categorie)
                    return (
                        <Menu.Item
                            key={`${index}`}
                            className={"left-menu_item"}
                            onClick={setCategory(categorie)}
                        >
                            <Link to={`/`}>{categorie}</Link>
                        </Menu.Item>
                    )
                })}
            </Menu>
        </PageHeader>
    )
}

希望您能帮助我,谢谢您

0 个答案:

没有答案