如何显示或隐藏我的子类别取决于使用REPACT-REDUX点击主类别?

2exbekwf  于 2022-10-01  发布在  其他
关注(0)|答案(1)|浏览(143)

如何编写显示和隐藏元素的操作逻辑。现在我的所有子类别显示,但我想显示主题后,用户点击Manin类别。假设用户点击电子类别,那么它应该只打开电子类别的所有子类别。如果用户点击另一个主类别,则前一个主类别应该是隐藏。以下是我的代码:。

export const adsSlice = createSlice({
  name: "ads_category",
  initialState,
  reducers: {
    // setProducts(state, action) {
    //     state.data = action.payload;
    // },
    // setStatus(state, action) {
    //     state.status = action.payload;
    // },
},
extraReducers: (builder) => {
    builder
        .addCase(fetchProducts.pending, (state, action) => {
            state.status = STATUSES.LOADING;
        })
        .addCase(fetchProducts.fulfilled, (state, action) => {
            state.data = action.payload;
            state.status = STATUSES.IDLE;
        })
        .addCase(fetchProducts.rejected, (state, action) => {
            state.status = STATUSES.ERROR;
        });
},
})

我的页面

const PostAds = () => {

  const dispatch = useDispatch();
  const display_category = useSelector(state=>state.ads)

  useEffect(() => {
    dispatch(fetchProducts());

}, []);

    return (
      <>.....</>)
vsdwdz23

vsdwdz231#

尝试为您的所有子类别创建布尔状态,然后创建一个带有CATEGORY参数的函数,然后切换哪个状态为TRUE。以下是实现的示例代码。

const [isMainCategory, setIsMainCategory] = useState(false)
const [isElectornics, setIsElectronics] = useState(false)

function handleShow(category){
    switch(category)
       case 'main-category':
           setIsMainCategory(true)
           setIsElectronics(false)
           break
       case 'electronics':
           setIsMainCategory(false)
           setIsElectronics(true)
           break
      default:
           setIsMainCategory(false)
           setIsElectronics(false)

}

return (
  <button onClick={() => handleShow('main-category')}>Main</button>
  <button onClick={() => handleShow('electronics')>Electronics</button>

  // this syntax here will check if your logic is true your component will show
  {isMainCategory && `your main category component`}
  {isElectrocnics && ` you electronics category component}
)

相关问题