reactjs - this.props.match.params 即使在传递参数时也是空的
问题描述
我试图在我的 React 组件中传递params
,this.props.match
但即使在传递之后我仍然得到params
空对象。
render() {
return (
<div>
<div className="boxx">
{this.state.data.map(ele => (
<div className="smallbox" key={ele.id}>
<Link
to={`${this.props.match.url}/movie1`}
onClick={() => this.fetchOneMovieData(ele)}
>
<img
src={`http://image.tmdb.org/t/p/w185${ele.poster_path}`}
alt="movie pic"
/>
</Link>
</div>
))}
<Route
path={`${this.props.match.url}/:topicId`}
render={props => (
<OneMovie
{...props}
data={this.state.data}
moviedata={this.state.moviedata}
/>
)}
/>
</div>
{console.log(this.props.match)}
</div>
);
}
解决方案
您必须使用Router
andwithRouter()
来访问props.match
例如,您可以像这样使用BrowserRouter
and withRouter
from react-router-dom
:
应用程序.js:
import MyComponent from "./MyComponent";
import {BrowserRouter, Route} from "react-router-dom";
class App extends Component {
render() {
return (
<div className="App">
<BrowserRouter basename='http://localhost:3000'>
<Route exact path='/:myparam' component={MyComponent}/>
</BrowserRouter>
</div>
);
}
}
export default App;
和 MyComponent.js:
从“react-router-dom”导入 {withRouter};
class MyComponent extends React.Component {
render() {
console.log('props match', this.props.match);
return <h1>MyComponent</h1>
}
}
export default withRouter(MyComponent);
从上面访问http://localhost:3000/asdf
应用程序会导致控制台输出:
道具匹配对象{路径:“/:myparam”,网址:“/asdf”,isExact:true,参数:{...}}
然后,您可以访问 :myparam on 的值,this.props.match.params.myparam
在此示例中为您提供:
自卫队
推荐阅读
- c++ - 如何传递函数指针(回调)并在不知道它的类型的情况下调用它?
- sql - MSSQL 错误:多部分标识符无法绑定
- maps - 在 Power BI Maps 上绘制状态字符串
- java - Micronaut AWS Lambda 日志未显示在云端
- javascript - 我可以更改扩展类中方法的返回类型吗?
- cmake - 如何解决才能正确编译?
- python - Python中CSV列表的索引错误,即使在获得输出之后
- hadoop - Hive/Impala 列评论在几个字符后被截断
- computation-theory - 这台给定机器的“正则表达式”是什么?
- excel - 在 VBA 中跨 Subs(w/in 模块)定义变量