[英]How to use react-router
我正在构建一个电影应用程序,它从themoviedb
API 中提取数据。 现在,在主页上,我有一个搜索表单,我可以在其中输入我想要查找的电影。 然后在下面,我用一个按钮显示返回的电影的结果,该按钮将您带到一个页面,该页面显示有关特定电影的更多信息。
我的问题是路由。 我如何做到这一点,当我在movie-details
页面上时,不显示search
和results
组件
import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";
import Navbar from "./navbar";
import Search from "./search";
import Result from "./result";
import Details from "./details";
import "./App.css";
import axios from "axios";
class App extends Component {
state = {
searchTerm: "",
movies: []
};
onSearch = e => {
e.preventDefault();
this.setState({ searchTerm: e.target.value });
};
handleSubmit = async e => {
e.preventDefault();
const result = await axios.get(
`https://api.themoviedb.org/3/search/movie?query=${this.state.searchTerm}&page=1&api_key=6f7ad5c4744feea1ee5508d2e56232c4`
);
this.setState({movies: result.data.results})
console.log(result.data.results);
};
render() {
return (
<div className="container">
<Navbar />
<Switch>
{/* <Search handleSearch={this.onSearch} /> */}
{/* <Route exact path="/" component={Search} handleSearch={this.onSearch} handleSubmit={this.handleSubmit}/> */}
= <Route
exact
path="/"
render={props => (
<Search
{...props}
handleSearch={this.onSearch}
handleSubmit={this.handleSubmit}
/>
)}
/>
<Route path="/movie/" component={Details} />
<Route path="/" component={Result} />
</Switch>
<Result movies={this.state.movies}/>
</div>
);
}
}
export default App;
你的<Result />
组件在路由器之外,所以它总是被显示。 这里的一个快速解决方法是将其移动到路由器内部,如下所示:
return (
<div className="container">
<Navbar />
<Switch>
{/* <Search handleSearch={this.onSearch} /> */}
{/* <Route exact path="/" component={Search} handleSearch={this.onSearch} handleSubmit={this.handleSubmit}/> */}
<Route
exact
path="/"
render={props => (
<>
<Search
{...props}
handleSearch={this.onSearch}
handleSubmit={this.handleSubmit}
/>
<Result movies={this.state.movies} />
</>
)}
/>
<Route path="/movie/" component={MovieDetails} />
</Switch>
</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.