我正在使用moviedb API来接收包含电影和电视节目的两个列表。我有两个按钮,可以将一个列表切换到另一个列表。 加载页面后,我想显示电影列表,然后通过单击电视节目按钮将其更改为电视节目列表。问题是当页面加载时没有电影列表,但是当我单击按钮以查看电视列表时 它会显示,当我单击“电影”按钮时,将显示电影列表。
我尝试使用不同的生命周期方法,但是它们无法正常工作。我猜该组件收到一个空数组,什么也没显示。如何解决?
class AdditionalActorInfo extends Component {
state = {
actor: [],
isMovieClicked: true,
isShowClicked: false
};
onMovieClick = () => {
this.setState({
isMovieClicked: true,
isShowClicked: false
});
};
onShowClick = () => {
this.setState({
isShowClicked: true,
isMovieClicked: false
});
};
componentDidMount() {
const { id } = this.props;
if (!id) {
return;
} else {
fetch(
`https://api.themoviedb.org/3/person/${id}?api_key=81f382d33088c6d52099a62eab51d967&language=en-US`
)
.then(res => res.json())
.then(data => {
this.setState({
actor: data
});
});
}
}
render() {
const { actor, isShowClicked, isMovieClicked } = this.state;
return (
<div className="actorInfo-container">
<div className="buttons">
<button onClick={this.onMovieClick}>Movies</button>
<button onClick={this.onShowClick}>TV Shows</button>
</div>
{isMovieClicked ? (
<MovieCredits id={actor.id} />
) : isShowClicked ? (
<ShowCredits id={actor.id} />
) : null}
</div>
);
}
}
export default AdditionalActorInfo;
class MovieCredits extends Component {
state = {
movieCredits: []
};
componentDidMount() {
const { id } = this.props;
if (!id) {
return;
} else {
fetch(
`https://api.themoviedb.org/3/person/${id}/movie_credits?api_key=81f382d33088c6d52099a62eab51d967&language=en-US`
)
.then(res => res.json())
.then(data => {
const movieCredits = data.cast
.map(item => {
return (
<li key={item.id} className="credit-list">
{item.release_date.slice(0, 4)}
<p>
<Link to={`/movieInfo/${item.id}`}>
<span>{item.title}</span>
</Link>
{item.character !== "" ? `as ${item.character}` : null}
</p>
</li>
);
});
this.setState({
movieCredits
});
})
.catch(e => console.log(e));
}
}
render() {
const { movieCredits } = this.state;
return (
<React.Fragment>
<ul>{movieCredits}</ul>
</React.Fragment>
);
}
}
export default MovieCredits;
class ShowCredits extends Component {
state = {
showCredits: [],
isLoading: true
};
componentDidMount() {
const { id } = this.props;
if (!id) {
return;
} else {
fetch(
`https://api.themoviedb.org/3/person/${id}/tv_credits?api_key=81f382d33088c6d52099a62eab51d967&language=en-US`
)
.then(res => res.json())
.then(data => {
console.log(data);
const showCredits = data.cast
.map(item => {
return (
<li key={item.id} className="credit-list">
{item.first_air_date.slice(0, 4)}
<p>
<Link to={`/movieInfo/${item.id}`}>
<span>{item.name}</span>
</Link>
{item.character !== "" ? `as ${item.character}` : null}
</p>
</li>
);
});
this.setState({
showCredits,
isLoading: false
});
})
.catch(e => console.log(e));
}
}
render() {
const { showCredits } = this.state;
return (
<React.Fragment>
<ul>{showCredits}</ul>
</React.Fragment>
);
}
}
export default ShowCredits;
答案 0 :(得分:0)
react setstate默认情况下是异步的,您必须通过在fetch方法中调用setstate使其同步。 它应该看起来像这样: .then(data =>()=> this.setstate({}))