[英]Post ID route showing up in other components
我正在學習路由器和redux。 我正在嘗試創建一個博客。 現在,帖子ID路徑顯示在“關於”和“投資組合”之類的其他組件中,但未顯示在主頁中,因為我已將其設置為精確路徑。
https://github.com/chiranjeebhub/router-redux
import React, { Component } from "react";
import { connect } from "react-redux";
class Post extends Component {
render() {
const post = this.props.post ? (
<div>
<h4>{this.props.post.title}</h4>
<p>{this.props.post.body}</p>
</div>
) : (
<div>
<p>loading post ... </p>
</div>
);
return <div>{post}</div>;
}
}
const mapStateToProps = (state, ownProps) => {
let id = ownProps.match.params.post_id;
return {
post: state.posts.find(post => post.id == id)
};
};
export default connect(mapStateToProps)(Post);
import React, { Component } from "react";
import { BrowserRouter, Route } from "react-router-dom";
import NavBar from "./Components/NavBar";
import Home from "./Components/Home";
import About from "./Components/About";
import Post from "./Components/post";
import Portfolio from "./Components/portfolio";
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<NavBar />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/:post_id" component={Post} />
</div>
</BrowserRouter>
);
}
}
export default App;
import React, { Component } from "react";
class About extends Component {
render() {
return (
<div>
<h1>About Me</h1>
</div>
);
}
}
export default About;
const initState = {
posts: [
{ id: "1", title: "title1", body: "body1" },
{ id: "2", title: "title2", body: "body2" },
{ id: "3", title: "title3", body: "body3" },
{ id: "4", title: "title4", body: "body4" }
]
};
const rootReducer = (state = initState, action) => {
return state;
};
export default rootReducer;
現在,當我加載“關於”組件時,會從post.js中顯示“正在加載帖子...”
您遇到了問題,因為路徑
<Route path="/:post_id" component={Post} />
表明在post_id
占位符處期望有一個動態值。 由於post_id
只是一個占位符,使用about
, portfolio
, 1
等作為路由參數將滿足條件。
即
// All of them are valid
/about
/portfolio
/1
因此Post
組件與其他組件一起顯示。
因此,您應該使用Switch
組件包裝Route
組件。 由於Switch
組件僅呈現與該路徑匹配的第一個子組件,因此使用/about
和/portfolio
時Post
組件將不會顯示。
import { BrowserRouter, Route, Switch } from 'react-router-dom';
<BrowserRouter>
<div className="App">
<NavBar />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/portfolio" component={Portfolio} />
<Route path="/:post_id" component={Post} />
</Switch>
</div>
</BrowserRouter>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.