反应路由器:更新道具

React router : update props

我是 React 新手,我有一个组件 UpdateInvoice,它有一个属性 idInvoice 和一个布尔值 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 发送正确的道具,因为 ListInvoicesidInvoiceisNew 信息

更新:

ListInvoices.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 变量包含我在这里设置的状态

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

This tutorial helped me