【发布时间】:2022-01-18 14:39:35
【问题描述】:
我有一个React 应用程序和组件结构如下所示
app.component.ts
<App>
<Products></Products>
</App>
product.component.ts
export const ProductComponent = () => {
const [category, setcategory] = useState("retail");
const [products, setProducts] = useState([]);
const categorySelectHandler = (selectedCategory:string) => {
setcategory(selectedCategory);
}
useEffect(() => {
getProductsByCategory(category).then((products) => {
setProducts(products);
}
});
}, [category]);
return (
<>
<CategorySelector onCategorySelected={categorySelectHandler }></CategorySelector>
{ products.map((product) => {
return (
<div>
<b> {product.name} </b>
<i> {product.price} </b>
}
</>}
categorySelector.component.ts
const CategorySelector: React.FC <CategorySelectorProps> = ({
onCategorySelected,
}) => {
const emptydata: Data[] = [];
const [category, setcategory] = useState("retail");
const [data, setdata] = useState(emptydata);
const categorySelectorHandler = (e: SyntheticEvent) => {
e.preventDefault();
const element = e.target as HTMLInputElement;
setcategory(element.value);
onCategorySelected(element.value);
};
return (
<div>
<select defaultValue = {category} onChange = {categorySelectorHandler} >
<option value = "retail" > Retail </option>
<option value = "electronics" > Electronics < /option>
</select>
{
data.map((_data: data) => {
return ( <a href = "#" > {
_data.name
} < /a> <
/div>
);
})
}
</div>
)};
export default CategorySelector;
这里onChange CategorySelector 组件中的下拉事件(子组件)我获取所选值并将其传递给父组件,即ProductComponent。
& 这反过来会触发对 API 的 ajax 调用,该调用将根据所选类别返回产品列表。
到此为止没有问题
现在在同一个事件中,我需要将产品列表传回给子组件,即CategorySelector
长话短说
在子组件中的事件上,将数据传递给父组件(这里没有问题),但是在同一个事件上,我需要将数据从父组件传回子组件组件。
【问题讨论】:
-
为什么需要将类别存储在两个组件的状态中?为什么不把它留在父组件中,作为道具发送给子组件呢?与产品相同。
-
3 个选项 1) 分解你的组件并有一个产品显示组件并通过道具传递 2) 在父级本身中显示产品 3) 如果你必须合并,那么你必须通过通过现有的
categoryselector产品的道具,并传递categoryselector选择的选项的值,因为您的categoryselector现在是一个受控组件,这可能很麻烦。选择 1 个选项 -
这是我的一个答案,可能有助于提升状态。 stackoverflow.com/questions/70397397/…。这遵循我上面评论中的#1 方法。我认为您的具体示例急需提升状态。
-
@SangeetAgarwal,请您检查并提出建议。谢谢! stackoverflow.com/questions/70851655/…
标签: javascript reactjs