[英]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 發送正確的道具,因為具有ListInvoices
和isNew
信息的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.