簡體   English   中英

反應路由器:更新道具

[英]React router : update props

我是新手,我有一個組件UpdateInvoice ,它具有道具idInvoice和 boolean isNew 如果isNew為真,該組件會做兩件事,該組件將添加新發票,否則,它將更新由其idInvoice的現有發票。

我還有ListInvoices組件。 我想當我點擊這個組件中的“NEW INVOICE”按鈕時,我將能夠調用我的UpdateInvoice所以我使用了React Router

問題

我從ListInvoices發送到UpdateInvoice的道具是空的!

index.tsx

root.render(
  
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="UpdateInvoice" element={<UpdateInvoice {...{idInvoice:'', isNew: null}} />} />
    </Routes>
  </BrowserRouter>,
);

ListInvoices.tsx

<Button 
   variant="contained" 
   className="add" 
   onClick={() => navigate("/UpdateInvoice", {state: {idInvoice: '', isNew: true }})} 
   startIcon={<AddIcon />}>
       NEW INVOICE
 </Button>

我無法從 index.tsx 發送正確的道具,因為具有ListInvoicesisNew信息的idInvoice

更新:

清單發票.tsx

 const [data, setData] = React.useState([] as any[]);

 //when the user is authenticated using an api, I update headers value  
 const [headers, setHeaders] = React.useState(
    { 
    'Authorization':  ``,
    'My-Custom-Header': ''
   });  

 useEffect(() => {
    if(headers.Authorization != ''){
      getData(); // I fetch data from an api 
    } 
  }, [headers])

const columns: GridColDef[] = [
{ field: 'idInvoice', headerName: 'ID', minWidth: 160 }, 
//more columns..
]

 return (
    <div>
      <Button 
         variant="contained" 
         className="add" 
         onClick={() => navigate("/UpdateInvoice", {state: {idInvoice: '', isNew: true }})} 
         startIcon={<AddIcon />}>
       NEW INVOICE
      </Button>

      <Paper sx={{width: '100%', p:1}} component="ul">
        <div style={{ height: 400, width: '100%'}}>
          {data.length != 0 ? 
          <DataGrid
            rows={data}
            columns={columns}
            pageSize={5}
            rowsPerPageOptions={[5]}
          /> : <CircularProgress className='progress'/>}
        </div>
      </Paper>
    </div>
  );

我所要做的就是使用useLocation鈎子

UpdateInvoice

  const location = useLocation();
  const [invoiceState, setInvoiceState] = React.useState<InvoiceProps>(location.state as InvoiceProps);

React.useEffect(() => {
    setInvoiceState(location.state as InvoiceProps);
  }, [location])

location變量包含我在這里設置的 state

<Button 
   variant="contained" 
   className="add" 
   onClick={() => navigate("/UpdateInvoice", {state: {idInvoice: '', isNew: true }})} 
   startIcon={<AddIcon />}>
       NEW INVOICE
 </Button>

本教程幫助了我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM