我想显示和隐藏依赖于父ID的子元素。假设如果用户点击父id->1,那么它应该显示父id->1的所有子元素。在我的项目中,我有很多父类别,每个父类别都有很多子类别。我有一个页面,在那里我显示了我的所有主要类别和子类别。但问题是,如果用户点击父类别->1,那么它会显示来自其他父类别的所有子类别。
以下是我的Redux切片器代码:
const { createSlice, createAsyncThunk } = require('@reduxjs/toolkit');
const STATUSES = Object.freeze(
{
IDLE: 'idle',
ERROR: 'error',
LOADING: 'loading'
}
)
const initialState = {
categories: [],
status: STATUSES.IDLE,
}
export const adsSlice = createSlice({
name: "ads_category",
initialState,
reducers: {
},
extraReducers: (builder) => {
builder
.addCase(fetchProducts.pending, (state, action) => {
state.status = STATUSES.LOADING;
})
.addCase(fetchProducts.fulfilled, (state, action) => {
state.categories = action.payload;
state.status = STATUSES.IDLE;
})
.addCase(fetchProducts.rejected, (state, action) => {
state.status = STATUSES.ERROR;
});
},
})
// Action creators are generated for each case reducer function
export const { ads_category, showcategory} = adsSlice.actions
export default adsSlice.reducer
// Thunks
export const fetchProducts = createAsyncThunk('ads_category/fetch', async () => {
const res = await fetch('http://localhost:8000/ads_category/');
const data = await res.json();
return data;
});
这是我的page.js
const PostAds = () => {
const [showcat, setShowCat] = useState(false)
const dispatch = useDispatch();
const show_data = useSelector(state=>state.ads)
useEffect(() => {
dispatch(fetchProducts());
}, []);
show_sub_category = ()=>{
setShowCat(true)
}
return (
<>
{/*showing all of my main category */}
{show_data.categories.map((data)=>(
<button onClick={show_sub_category}>
{data.main_category}
</button>
{showcat &&
{/*showing all of my sub category */}
{data.sub_cat_bp.map((data)=>({data.sub-category}))}
}
))}
下面是我从redux获取的API数据:
[
{
"id": 1,
"main_category": "Electronic",
"main_city": "Dhaka",
"sub_cat_bp": [
{
"sub_category": "mobile",
"sub_city": "Dhanmondi",
"id": 1
},
{
"sub_category": "Charger",
"sub_city": "Dhanmondi",
"id": 2
},
{
"sub_category": "Headphone",
"sub_city": "Lalbagh",
"id": 3
}
]
},
1条答案
按热度按时间x8diyxa71#
当您Mapshow_data.ategories.map()之类的show_data.ategories.map()时,您应该得到一个main_ategory的id(data.id)。将主类别的id存储在一个状态(ClickedCategoryID)中。在Map内部,检查clickedCategoryID是否等于data.id。如果等于,则显示data.sub_cat_bp.map((data)=>({data.sub-category}))
修改后的代码如下:
让我知道它是否起作用