我尝试在三个全局视图中保留状态。
我拥有MovieRow
,收藏夹和Popular
组件中的组件Search
。目的是在此视图中调用组件MovieRow
时保持其状态(Popular
...
例如,如果我有2部电影,我检查了一部电影以将其添加到收藏夹,则该电影应保持状态。现在,如果我单击并更改全局视图时将电影添加到收藏夹列表,则组件MovieRow
将再次安装并重置状态。
我尝试了许多不同的方法。将状态1全局变量与条件渲染存储到我的MovieRow
以及其他状态。
编辑:您可以在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
MoviesRow.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}