【发布时间】:2020-03-21 19:37:59
【问题描述】:
所以我正在开发一个 React 应用程序,但我已经被一个问题困扰了两天。我正在构建一个从 TMDB 获取数据的搜索,并且一切正常。当我输入输入时,所有数据都会流入!但是,当我提交并尝试重定向到 /results 页面时,该页面链接到一个组件,该组件在定向到时显示搜索结果,但它重定向到结果页面,我无法显示搜索结果。这是我的代码。
import React, { Component, Redirect } from "react";
import axios from "axios";
import { withRouter } from "react-router";
constructor(props) {
super(props);
this.state = {
results: [],
term: ""
};
this.submit = this.submit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidUpdate(prevProps, prevState) {
const { history } = this.props;
if (prevState.results !== this.state.results) {
history.push("/results");
}
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
console.log(this.state);
}
submit(e) {
e.preventDefault();
const term = e.target.elements.term.value;
let url = `https://api.themoviedb.org/3/search/tv?api_key=6d9a91a4158b0a021d546ccd83d3f52e&language=en-US&query=${term}&page=1`;
axios
.get(url)
.then(({ data }) => {
// const info = response.data.results;
console.log(data);
this.setState({
results: data
});
})
.catch(error => console.log(error));
}
render() {
return (
<div>
<form onSubmit={this.submit}>
<input
onChange={this.handleChange}
type="text"
name="term"
value={this.state.term}
/>
<button type="submit" bsStyle="primary">
Find
</button>
</form>
</div>
);
}
}
export default withRouter(Find);
和Result.js
<div className="search-poster-container">
{this.props.results.map(result => { // This error show how to reolve this
<p>{result.name}</p>
})}
<h1>Hello Result will fetch here</h1>
</div>
【问题讨论】:
-
执行是否到达
if内componentDidUpdate内的代码?
标签: javascript reactjs react-native redirect react-router