我想将电影的状态保存在本地存储中。我被困住了,不知道如何实现这一点。我试图在App组件的addMovie方法中添加localStorage.setItem('movies', JSON.stringify(this.state.movies))
,但这不起作用。我在下面列出了我的App组件和CreateMovieForm组件。
此网站将电影存储在列表中。该网站的工作方式是在应用程序组件中具有电影状态。所有组件所做的就是操纵此电影状态。他们是否删除或添加电影都没有关系。状态始终会更新,电影列表也会重新呈现。
class App extends React.Component {
constructor(props){
super(props)
this.state = {
movies: []
}
}
addMovie(movie) {
this.setState({
movies: this.state.movies.concat(movie)
})
console.log(this.state.movies);
}
createDeltedList(newMovies){
this.setState({
movies: newMovies
})
}
sortMovies(){
let movies = this.state.movies;
movies.sort(function(a, b) {
return b.grade - a.grade;
})
this.setState({movies: movies})
}
sortMoviesAlpha(){
let movies = this.state.movies;
movies.sort(function(a, b) {
if (a.title > b.title){
return 1
}
if (a.title < b.title){
return -1
}
return 0
})
this.setState({movies: movies})
}
render(){
return (
<div className='container'>
<AppTitle attr='display-4' title='Min film lista ' />
<LeadText attr='lead' text='Lägg till film:' />
<AddLine />
<CreateMovieForm addMovie={this.addMovie.bind(this)} attr='form-group' from='form-control' btnSave='Spara film'/>
<SortGradeButton sortMovies={this.sortMovies.bind(this)} text='Sort by Grade'/>
<SortAlphaButton sortMoviesAlpha={this.sortMoviesAlpha.bind(this)} text='Sort Alphabetically' />
<MovieList genNewList={this.createDeltedList.bind(this)} movies={this.state.movies} />
</div>
);
}
}
export default App;
class CreateMovieForm extends React.Component{
constructor(props){
super(props);
this.state = {title: '', grade: '1'};
this.handleTitleChange = this.handleTitleChange.bind(this);
this.handleGradeChange = this.handleGradeChange.bind(this);
this.handleSave = this.handleSave.bind(this);
}
handleTitleChange(event) {
this.setState({title: event.target.value});
}
handleGradeChange(event){
this.setState({grade: event.target.value});
}
handleSave(event){
event.preventDefault();
let movie = {
title: this.state.title,
grade: this.state.grade
}
this.props.addMovie(movie)
}
render(){
return (
<form onSubmit={this.handleSave}>
<div className={this.props.attr}>
<label htmlFor='movieTitle'>Titel:</label>
<input type='text' className={this.props.from} placeholder='Titel här...' title={this.state.title} onChange={this.handleTitleChange}/>
</div>
<div className={this.props.attr}>
<label htmlFor='grade'>Betyg:</label>
<select id='grade' className={this.props.from} grade={this.state.grade} onChange={this.handleGradeChange}>
<option>Välj betyg här...</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<button className='btn btn-info'>{this.props.btnSave} </button>
</form>
);
}
}