我尝试让组件返回2个带条件的条件,但是出现错误:
Objects are not valid as a React child (found: object with keys {movie}). If you meant to render a collection of children, use an array instead.
我阅读了几乎相同主题的其他子喷气机,我试图用她的解决方案纠正我的错误,但没有成功。
没有尝试的基本代码。这些函数所关心的(我尝试渲染)是IsFav
IsNotFav
。
fils.js:
import React from "react";
import "../css/MovieRow.css";
import { APIKEY, baseURL } from "../../App";
var myFavoriteMovies = [];
function IsFav(props) {
return (
<div key={this.props.movie.id} className="MovieRow">
<div>
<img alt="poster" src={this.props.posterSrc} />
</div>
<div>
<h3>{this.props.movie.title}</h3>
<p>{this.props.movie.overview}</p>
<input type="button" onClick={this.viewMovie.bind(this)} value="View" />
<button onClick={props.onClick} className="heart" />
</div>
</div>
);
}
function IsNotFav(props) {
return (
<div key={this.props.movie.id} className="MovieRow">
<div>
<img alt="poster" src={this.props.posterSrc} />
</div>
<div>
<h3>{this.props.movie.title}</h3>
<p>{this.props.movie.overview}</p>
<input type="button" onClick={this.viewMovie.bind(this)} value="View" />
<button onClick={props.onClick} className="toggled heart" />
</div>
</div>
);
}
class MovieRow extends React.Component {
constructor(props) {
super(props);
this.addFavorite = this.addFavorite.bind(this);
this.deleteFavorite = this.deleteFavorite.bind(this);
this.state = { isFaved: false };
}
viewMovie() {
const url = "https://www.themoviedb.org/movie/" + this.props.movie.id;
window.location.href = url;
}
addFavorite() {
this.setState({ isFaved: true });
const favMovie = "".concat(
baseURL,
"movie/",
this.props.movie.id,
"?api_key=",
APIKEY
);
myFavoriteMovies.push(favMovie);
}
deleteFavorite() {
this.setState({ isFaved: false });
}
render() {
const isFaved = this.state.isFaved;
let movie;
if (isFaved) {
movie = <IsNotFav onClick={this.deleteFavorite} />;
} else {
movie = <IsFav onClick={this.addFavorite} />;
}
return { movie };
}
}
export { MovieRow as default, myFavoriteMovies };
答案 0 :(得分:3)
您正在从{ movie: movie }
渲染方法返回对象MovieRow
。只需直接返回JSX:
render() {
const isFaved = this.state.isFaved;
let movie;
if (isFaved) {
movie = <IsNotFav onClick={this.deleteFavorite} />;
} else {
movie = <IsFav onClick={this.addFavorite} />;
}
return movie;
}
答案 1 :(得分:1)
return { movie }
存在问题,您无需将movie
放在{ }
内