gpt4 book ai didi

javascript - 无法通过 react 路由器 dom v6 beta 传递状态,状态为空

转载 作者:行者123 更新时间:2023-12-05 00:24:42 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to pass data from a page to another page using react router

(4 个回答)


3个月前关闭。




应用程序.js 文件

export default function App() {
return (
<div className="h-100">
<Routes>
<Link to={
{
pathname: "/posts",
state: {test: 'test'}
}
}>Posts</Link>
<Route path="/" element={<Home/>}/>
<Route path="/login" element={<Login/>}/>
<Route path="/posts" element={<Posts/>}/>
</Routes>
</div>
)
}
期望传递状态,一些数据从一页到另一页
当使用 useLocation 从另一个页面获取状态时,状态为 null
index.js 文件
import {BrowserRouter as Router} from "react-router-dom";
import App from "./App";

ReactDOM.render(
<React.StrictMode>
<Router>
<App/>
</Router>
</React.StrictMode>
,
document.getElementById('root')
);
Posts.js 文件
const location=useLocation()
console.log(location);
输出
Object { pathname: "/posts", search: "", hash: "", state: null, key: "hpuuzep5" }
包.json
{
"name": "chance",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.5",
"@testing-library/user-event": "^12.6.3",
"axios": "^0.21.1",
"bootstrap": "^5.0.0-beta3",
"history": "^5.0.0",
"ramda": "^0.27.1",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.2",
"styled-components": "^5.2.3",
"web-vitals": "^1.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
我不能从 react-router-dom 导入交换机,它说交换机不是从 react 路由器 dom 导出的,我认为已经正确设置了我的路由,错误在哪里,我无法将状态从一条路由传递到另一条路由

最佳答案

我可以通过这样做获得状态:

<Link
to={"/posts"}
state={{test: 'test'}}>
Posts
</Link>
我打开了类型声明,终于意识到 state 是一个 Prop ,而不是对象 https://github.com/ReactTraining/react-router/blob/dev/docs/api-reference.md#link 的一部分

关于javascript - 无法通过 react 路由器 dom v6 beta 传递状态,状态为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67061088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com