1
我想使用react
和react-router-dom
來訪問我的應用程序導航上的匹配參數。這裏是一個簡單的例子,我做了一個代碼,你可以在主題組件上看到我在組件級別獲得正確的匹配,但不在導航欄中,我在位置道具中獲得正確的url路徑,所以我不是當然,如果我這樣做是正確的。如何讓路由器將匹配參數傳遞給組件?
This would be the working snippet,因爲我無法將react-router-dom
添加到堆棧溢出片段。
import { BrowserRouter as Router, Route, Link, withRouter } from "react-router-dom";
const BasicExample = (props) =>
<Router>
<div>
<Nav/>
<hr />
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
</div>
</Router>;
const About =() => (
<div>
<h2>About</h2>
</div>
);
const Home =() => (
<div>
<h2>Home</h2>
</div>
);
const Navigation = (props) => (
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
<li>{`match prop -> ${JSON.stringify(props.match)}`}</li>
<li>{`location prop -> ${JSON.stringify(props.location)}`}</li>
</ul>
);
const Nav = withRouter(Navigation);
const Topic = ({ match, location }) => (
<div>
<h3>{match.params.topicId}</h3>
<li>{`match prop -> ${JSON.stringify(match)}`}</li>
<li>{`location prop -> ${JSON.stringify(location)}`}</li>
</div>
);
const Topics = ({ match, location, history }) => (
<div>
<h2>Topics</h2>
<li>{`match prop -> ${JSON.stringify(match)}`}</li>
<li>{`location prop -> ${JSON.stringify(location)}`}</li>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/components`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic} />
<Route
exact
path={match.url}
render={() => <h3>Please select a topic.</h3>}
/>
</div>
);
ReactDOM.render(<BasicExample />, document.getElementById("root"));
<body>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</body>
我看,我認爲這是從'' 傳下來的信息。你不會碰巧知道如何去做我想做的事,不是嗎? :) –
piptin
我想我不明白...你在props.location中有足夠的信息,或者你在props.match中找到了什麼? (這正是它應該如何) – Melounek
我想要從導航欄訪問 組件中的':topicId'參數,以便將某些項添加到導航中以確定是否存在某些參數。例如,我在URL中使用數據庫ID,如果它們來自一個數據庫或另一個數據庫,我無法辨別它,除非我擁有參數名稱。 –
piptin