我尝试为我的组件提供 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 };
最佳答案
您将从 MovieRow
渲染方法返回一个对象 { movie: movie }
。只需直接返回 JSX 即可:
render() {
const isFaved = this.state.isFaved;
let movie;
if (isFaved) {
movie = <IsNotFav onClick={this.deleteFavorite} />;
} else {
movie = <IsFav onClick={this.addFavorite} />;
}
return movie;
}
关于javascript - 1 组件 2 有条件返回。如何渲染子集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51359124/