将状态传递给另一个组件

Passing state to another component

在我的 MUI 中 Table 当在该行上单击 时,我将用户导航到另一个页面。是否可以选择直接使用 useNavigate 从行中传递数据,而不是使用 localStorage

  <TableBody>
                    {data &&
                        data.map((row, index) => (
                            <TableRow
                                hover
                                key={index}
                                onClick={(e) => {
                                    navigate('/assets-list') // <====== From here it Start 
                                     window.localStorage.setItem('selectedAsset', row); 
                                }}
                                sx={{ cursor: 'pointer' }}
                            >
                                <TableCell size="small">
                                    <Typography align="left" variant="subtitle1" component="div">
                                        {row.ASSET_NAME}
                                        <Typography variant="subtitle2">{row.ASSET_TYPE_NAME}</Typography>
                                    </Typography>
                                </TableCell>
                                <TableCell>
                                    <Typography align="left" variant="subtitle1" component="div">
                                        {row.BRAND}
                                    </Typography>
                                </TableCell>
                            </TableRow>
                        ))}
                </TableBody>

您可以在 useNavigate 钩子中将状态作为可选的第二个参数传递。

onClick={(e) => {
  navigate('/assets-list', { state: row })
}}

我们可以通过使用 useLocation 挂钩在您的 AssetsList 组件中访问:

const { state } = useLocation();
console.log(state);