我正在尝试制作一个网络应用程序。基本上,我尝试使用 ReactRouter 来显示作为路由参数传递的内容。但是,我无法做到这一点。为了检查是否有问题,我决定console.log出this.props.match,但仍然没有任何显示。有人可以解释一下问题是什么吗?还有可能绕过吗?
我的代码是-
import React from 'react';
export default class Post extends React.Component {
state = {
id: null
}
componentDidMount(props) {
console.log(this.props.match);
}
render = () => {
return (<div>Hello WOrld</div>)
}
}
App.js 文件:
import React, { Fragment, Component } from 'react';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Contact from './components/Contact';
import About from './components/About'
import Post from './components/Post';
import { BrowserRouter, Route } from 'react-router-dom';
class App extends Component {
render = () => {
return (
<BrowserRouter>
<div className="App">
<Navbar />
<Route exact path="/" component={Home} />
<Route path="/contact" component={Contact} />
<Route path="/about" component={About} />
<Route path="/:post-id" component = {Post} />
</div>
</BrowserRouter>
);
}
}
export default App;
最佳答案
我刚刚在我这边运行了你的代码,看起来问题出在使用/:post-id
。我将其更改为 /:pid
并且它起作用了。当我控制台日志 this.props.match
{
"path":"/:pid",
"url":"/1",
"isExact":true,
"params":
{
"pid":"1"
}
}
我希望这会有所帮助。
关于javascript - 无法使用 Link 来 console.log 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61183006/