這應該是一件容易的事。如何從 React 組件類中訪問 props.match?下面的第 17 行包含罪魁禍首。
編輯:我試圖從 URL 訪問 ID 引數。再次編輯以添加更多相關代碼
我不相信該withRouter解決方案在最新版本的 react-router-dom 中可用...
此外,useParams不能在類組件中使用...
post-detail.js,見第 17 行
5 class Post extends React.Component {
6 constructor(props) {
7 super(props);
8 this.state = {
9 title: '',
10 content: ''
11 };
12 }
13
14 componentDidMount() {
15 let api = new Api();
16
17 api.posts(this.props.match.params.id).then(data => {
18 this.setState({
19 title: data.title.rendered,
20 content: data.content.rendered
21 });
22 });
23 }
24
25 render() {
26 let post = this.state;
27 return (
28 <div className='row'>
29 <h3>{post.title}</h3>
30 <div dangerouslySetInnerHTML={{__html: post.content}} />
31 </div>
32 );
33 }
34 }
35
36 export {Post};
app.js,見第 27 行
10 class App extends React.Component {
11
12 constructor() {
13 super();
14 this.state = {
15 posts: []
16 };
17 }
18
19 componentDidMount() {}
20
21 render() {
22 return (
23 <div className="container">
24 <h1>hello world</h1>
25 <Routes>
26 <Route exact path='/' element={<PostList />} />
27 <Route path='/post/:id' element={<Post />} />
28 </Routes>
29 </div>
30 );
31 }
32 }
33
34 export default App;
索引.js
8 ReactDOM.render(
9 <React.StrictMode>
10 <HashRouter>
11 <App />
12 </HashRouter>
13 </React.StrictMode>,
14 document.getElementById('root')
15 );
uj5u.com熱心網友回復:
請配合路由器使用。
import { withRouter } from 'react-router-dom'
....
export default withRouter(Post)
uj5u.com熱心網友回復:
罪魁禍首在 <Route path='/post/:id' element={<Post />} />
您是否嘗試過使用component標簽?像下面這樣的東西
<Route path='/post/:id' component={Post} />
uj5u.com熱心網友回復:
看起來您可能使用的是版本 6 react-router-dom(截至目前的最新版本)
你可以使用一個鉤子,叫做 useParams()
結帳以下鏈接以獲取更多詳細資訊
https://reactrouter.com/docs/en/v6/api#useparams
uj5u.com熱心網友回復:
也許,您正在使用版本 6 的 react-router-dom。
然后,利用useParams,代碼是這樣的。
路線:
<Route path="invoices" element={<Invoices />}>
<Route path=":invoiceId" element={<Invoice />} />
</Route>
path=":invoiceId" :認為 url 'http://site/..../invoices/123'
關聯:
這使得路徑導航。
<Link
style={{ display: "block", margin: "1rem 0" }}
to={`/invoices/${invoice.number}`}
key={invoice.number}
>
{invoice.name}
</Link>
利用:
import { useParams } from "react-router-dom";
export default function Invoice() {
let params = useParams();
return <h2>Invoice: {params.invoiceId}</h2>;
}
請訪問這里并了解更多資訊。 https://reactrouter.com/docs/en/v6/getting-started/tutorial#reading-url-params
對你有幫助,我也很高興。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/403740.html
標籤:
上一篇:理解反應函式符號
