javascript - 如何使用反应路由器
问题描述
我正在构建一个从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>
);
推荐阅读
- javascript - 使用 selenium 抓取数据,提供启用 Javascript 消息
- javascript - 禁用将在未来月份以角度形式出现的输入文本字段
- split - 非英文文本的标签拆分器
- zip - 如何在 React admin 上创建 zip 功能
- oauth - 如何使用 openssl 解密 oauth 签名(使用 ec256 加密的 digist)
- python - 在 SQLAlchemy 中,按降序获取数据或 reverse() 列出获取的数据哪个更好?
- git - 使用 GitHub 操作将拉取请求合并到主服务器时,使用什么可预测的提交 sha?
- javascript - 如何使用 javascript 更改 svg 文件的属性?
- c# - cmd.executescalar() 有效但抛出 ORA-25191 异常
- ruby-on-rails - 在 rails 中设置全局参数在 rails 中无法正常工作