【发布时间】:2018-10-28 21:17:01
【问题描述】:
编辑:我找到了解决方案,我忘记了 routes.js 中的 switch 组件
我已经创建了这样的路线:/post/:id
我的routes.js 看起来像:
import React, { Component } from "react";
import { BrowserRouter, Route } from "react-router-dom";
import Posts from "./components/Posts";
import Post from "./components/Post";
class Routes extends Component {
render() {
return (
<div>
<BrowserRouter>
<div>
<Route exact path="/" component={Posts} />
<Route path="/post/:id" component={Post} />
</div>
</BrowserRouter>
</div>
);
}
}
export default Routes;
在我的/route 我列出了我所有的posts,当我点击其中一个时,我会更新网址http://localhost:3000/post/1。
PS:我尝试使用 react-router 官方文档中所说的 withRouter 函数,但这种情况不适用于我的情况。
有问题的文件是post.js 它看起来像:
import React, { Component } from "react";
import { active_post } from "../actions/index";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
class Post extends Component {
componentWillMount() {
this.props.active_post(this.props.match.params.id);
}
render() {
console.log(this.props.post);
return (
<div>
<h1>Detail d'un post</h1>
<p>{this.props.match.params.id}</p>
</div>
);
}
}
function mapStateToProps(state) {
return {
post: state.activePost
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ active_post }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Post);
因此,例如,如果我在 URL 栏中手动输入 http://localhost:3000/post/3,例如,我有组件和 console.log() 以及我需要的帖子。
因此,如果您对此案有解决方案,我会接受。 谢谢你:)
【问题讨论】:
标签: javascript reactjs redux react-router-dom