我正在尝试从子组件执行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
};
PageMenu
在useState
中使用:
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>
)
}
希望您能帮助我,谢谢您