AxS*_*Sch 2 javascript reactjs react-router
I am using react-router-dom together with react functional components. I am trying to pass data with "history.push", which is not working.
The redirection to another page with "history.push" itself is working great. BUT the problem is: passing data via "state: {...}" to a component causes: "Cannot read property 'state' of undefined" when I try to access it with "props.location.state" within the component.
I have tried different variations of defining the route.
import React from 'react';
import PageList from './pages/PageList';
import PageEdit from './pages/PageEdit';
import { BrowserRouter as Router, Route, Switch} from "react-router-dom";
export default function App() {
return (
<Router>
<Switch>
<Route exact path="/"> <PageList /> </Route>
<Route path="/edit"> <PageEdit/> </Route>
</Switch>
</Router>
);
}
Run Code Online (Sandbox Code Playgroud)
import React from 'react';
import { useHistory } from "react-router-dom";
import Button from '@material-ui/core/Button';
export default function PageList() {
let history = useHistory();
function handleTestClick(e) {
history.push({
pathname: "/edit",
state: {id: 123}
});
}
return (
<div>
<Button onClick={handleTestClick}>Test</Button>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
import React, { useEffect } from 'react';
export default function PageEdit(props) {
const test = props.location.state;
console.log("Meine ID:" + test.id);
return (
<div>
<h1>Edit Page</h1>
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
useEffect(() => {
const test = props.location.state;
console.log("Meine ID:" + test.id);
}, []);
Run Code Online (Sandbox Code Playgroud)
<Route exact path="/" component={PageList}> </Route>
<Route path="/edit" component={PageEdit}> </Route>
Run Code Online (Sandbox Code Playgroud)
<Route exact path="/" component={PageList} location={props.location}> </Route>
<Route path="/edit" component={PageEdit} location={props.location}> </Route>
Run Code Online (Sandbox Code Playgroud)
<Route exact path="/" component={PageList}> <PageList {...props}/> </Route>
Run Code Online (Sandbox Code Playgroud)
Nothing worked
我希望 console.log(...) 的输出是通过 history.push 传递的数据。考虑应该以这种方式工作的反应路由器的文档。
任何人都可以帮忙吗?
在 PageEdit.js 上,
您应该使用 useLocation() 访问状态
import {useLocation} from 'react-router-dom'
const location = useLocation()
console.log(location.state)
Run Code Online (Sandbox Code Playgroud)
您将能够访问您的数据
| 归档时间: |
|
| 查看次数: |
7907 次 |
| 最近记录: |