我试图从三个全球视角来保护国家。
我有组件
MovieRow
在
Popular
,收藏和
Search
组件。目标是该组件
电影
在此视图中调用时保留其状态(
流行
……)
例如,如果我有两部电影,我选中了一部要添加到最喜爱的电影,则该电影应保持状态。现在,如果我在单击并更改全局视图时将电影添加到收藏列表,则组件
电影
将再次装载并重置状态。
我尝试了很多不同的方法。存储状态一个全局变量,条件呈现为
电影
以及其他。
编辑:您可以在这里看到完整的代码
https://codesandbox.io/s/lpjp0oxmmq
编辑2:我成功地存储了我的状态,但无法成功地正确使用。
componentWillUnmount () {
let storeState = localStorage.setItem('someSavedState', JSON.stringify(this.state))
console.log(" ------------------- unmount ------------------- ")
console.log(JSON.parse(localStorage.getItem('someSavedState')))
console.log(" ------------------- ------- ------------------- ")
}
componentWillMount() {
const rehydrate = JSON.parse(localStorage.getItem('someSavedState'))
console.log(" ------------------- will mount ------------------- ")
console.log(rehydrate)
console.log(" ------------------- ---- ----- ------------------- ")
// this.setState({isFaved: rehydrate})
}
你知道谁帮我吗?
我们看到国家在这张照片中迷路了。取决于状态的按钮的颜色已重置。
View popular with the first movie added to fav
view favorite with fav movie
电影Row.js:
import React from 'react'
import '../css/MovieRow.css';
import { APIKEY, baseURL } from '../../App'
import { filter } from '../../View/Popular'
var myFavoriteMovies = []
function IsFav(props) {
return (
<div movieId={props.movie.id} className="MovieRow">
<div>
<img alt="poster" src={props.posterSrc} />
</div>
<div>
<h3>{props.movie.title}</h3>
<p>{props.movie.overview}</p>
<input type="button" value="View"/>
<button onClick={props.onClick} className=" heart">
</button>
</div>
</div>
);
}
function IsNotFav(props) {
return (
<div movieId={props.movie.id} className="MovieRow">
<div>
<img alt="poster" src={props.posterSrc} />
</div>
<div>
<h3>{props.movie.title}</h3>
<p>{props.movie.overview}</p>
<input type="button" value="View"/>
<button onClick={props.onClick} className="toggled heart">
</button>
</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
console.log(this.props.movie.id)
}
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 movie={this.props.movie} posterSrc={this.props.posterSrc} onClick={this.deleteFavorite}/>
} else {
movie = <IsFav movie={this.props.movie} posterSrc={this.props.posterSrc} onClick={this.addFavorite}/>
}
return movie
}
}
export { MovieRow as default, myFavoriteMovies}