ReactJS:根据下拉选择渲染不同的组件

问题描述 投票:0回答:1

我正在努力进行更改,通过基于下拉选择(动态)调用不同的 API 从数据源获取数据。

  • 如果我使用“ProductTable”组件,我可以在 UI 中查看数据 单独在“SelectEnvironment.js”中,并通过在“index.js”中硬编码“PROD1 URL” (获取产品)。

但是我遇到了以下用例:

  1. 可以说,单独考虑客户组件,根据下拉列表中的选择类型(prod1/prod2),动态需要获取相应的环境 URL 并且应该在 fetch 调用中使用。而不是为每个环境添加重复的代码(通过硬编码) URL)来获取数据。

  2. 基于菜单单击(通过单击产品/客户),它应该访问“SelectEnvironment.js”,并基于特定组件(产品/客户)的下拉选择,动态系统应该获取 API URL 并执行提取调用。

需要专家帮助才能实现。提前致谢。

菜单.js:

  const Menu = () => {
    return (
      <div className='menu'>
          <div className='item'>
             <Stack alignItems='center' direction='row'> 
                <Typography variant='body1'>Details</Typography>
             </Stack>
             <Link to="/product">
                <Typography variant='body1'>Product</Typography>
             </Link>
             <Link to="/customer">
                <Typography variant='body1'>Product</Typography>
             </Link>
          </div>
      </div>
    )
  }

App.js:

function App () {
  const router = createBrowserRouter ([
    {
     path: "/product"
     element: <SelectEnvironment />
    },
    {
     path: "/customer"
     element: <SelectEnvironment />
    },
    { 
     path: "/account"
     element: <SelectEnvironment />
    }
  ]);
 return (<RouterProvider router={router});
}
export default App;

选择环境.js:

function SelectEnvironment() {
   const[environment, setEnvironment] = useSate ("selectEnvironment");
   const[prod1DetailsVisible, setProd1DetailsVisible] = useSate (false);
   const[prod2DetailsVisible, setProd2DetailsVisible] = useSate (false);

   const handleOnChange = (event) => {
    setEnvironment(event.target.value);
   }

   useEffect (() => {
     environment === 'prod1' ? setDevDetailsVisible (true) : setDevDetailsVisible(false);
     environment === 'prod2' ? sitDetailsVisible (true) : sitDetailsVisible(false);
   }

   return (
      <div className='environment selection'>
        <div>
          <Typography variant='body1'> Select </Typography>
        </div>

        <div className='environment list'>
          <select className='form select' value ={environment} onChange={handleOnChange}>
             <option value='selectEnvironment'>select</option>
             <option value='prod1'>PROD1</option>
             <option value='prod2'>PROD2</option>
          </select>
        </div>
        {prod1DetailsVisible && < ProductTable/>}
        {prod2DetailsVisible && < ProductTable/>}
     </div>
    )
}
export default SelectEnvironment;

产品表.js:

   function ProductTable() {
       const dispatch = useDispatch();
       const list = useSelector((state) => state.product.products);
       
       useEffect (() => {
          dispatch(getProduct ());
       },[]);

       return (
          <>
            <Grid container>
              <Grid item xs={12}>
                <TableContainer component ={paper}>
                  <Table sx={{mnWidth:650}} aria-label='simple table'>
                    <TableHead>
                       <TableRow>
                          <TableCell>
                            <b> Product Id </b>
                          </TableCell>
                          <TableCell>
                            <b> Product Name </b>
                          </TableCell>
                       </TableRow>
                    </TableHead>
                    <TableBody>
                       {
                         list.map((row) => (
                           <TableRow key={row?.id}>
                              <TableCell component='th' scope='row'>{row?.id}</TableCell>
                              <TableCell >{row?.name}</TableCell>
                           </TableRow>
                       ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Grid>
            </Grid>
          </> 
       );
   }
   export default ProductTable;

客户.js

function CustomerTable() {
       const dispatch = useDispatch();
       const list = useSelector((state) => state.customer.customers);
       
       useEffect (() => {
          dispatch(getCustomer ());
       },[]);

       return (
          <>
            <Grid container>
              <Grid item xs={12}>
                <TableContainer component ={paper}>
                  <Table sx={{mnWidth:650}} aria-label='simple table'>
                    <TableHead>
                       <TableRow>
                          <TableCell>
                            <b> Customer Id </b>
                          </TableCell>
                          <TableCell>
                            <b> Customer Name </b>
                          </TableCell>
                       </TableRow>
                    </TableHead>
                    <TableBody>
                       {
                         list.map((row) => (
                           <TableRow key={row?.id}>
                              <TableCell component='th' scope='row'>{row?.id}</TableCell>
                              <TableCell >{row?.name}</TableCell>
                           </TableRow>
                       ))}
                    </TableBody>
                  </Table>
                </TableContainer>
              </Grid>
            </Grid>
          </> 
       );
   }
   export default CustomerTable;

存储->操作->index.js

    export const getProduct = () => (dispatch) => {
         fetch ("Product URL").then ((response) => response.json())
         .then((data) => {
           dispatch ({type:GET_PRODUCT, payload:data}); 
         }) 
         .catch(error) => console.log(error));
     };

     export const getCustomer = () => (dispatch) => {
         fetch ("Customer  URL").then ((response) => response.json())
         .then((data) => {
           dispatch ({type:GET_CUSTOMER, payload:data}); 
         }) 
         .catch(error) => console.log(error));
     };

存储->减速器->type.js

  const initialState = {
     products :[];
  };
  
 const initialStateCust = {
     customers :[];
  };

  const product = (state=initialState, action) => {
       switch(action.type) {
          case GET_PRODUCT:
              return {...state, product: action.payload};
        }
   };

   const customer = (state=initialStateCust, action) => {
       switch(action.type) {
          case GET_CUSTOMER:
              return {...state, customer: action.payload};
        }
   };
 export default product;

reactjs react-native react-hooks react-redux react-router
1个回答
0
投票

这可以通过使用 hashmap 方法轻松完成,您只需获取数据并应用于地图即可。请参阅下面的示例。

// mock data

const links = [
  {
    title: 'Services',
    url: '/Services',
    submenu: [
      {
        title: 'Cloud',
        url: '/services/cloud',
      },
      {
        title: 'SEO',
        url: '/services/seo',
      },
    ],
  },
  {
    title: 'Who we are',
    url: '/about',
  },
]

 // Map the data and apply to the links

{links.map((items, index) => (
        <li key={index}>
          <a href={items.url} onClick={linkClick}>
            {items.title} <ArrowIconForward />
          </a>
        </li>
      ))}

© www.soinside.com 2019 - 2024. All rights reserved.