简体   繁体   English

这是在 localStorage 中存储数据列表并在使用 React 应用程序搜索时显示它们的最佳方式

[英]Which is the best way to store a list of data in localStorage and display them when searched using a React app

I'm trying to build a movie directory kinda like a todo-list app but here you can store your favorite movies and can search and display them by searching with the name of the movie.我正在尝试构建一个类似于待办事项列表应用程序的电影目录,但在这里您可以存储自己喜欢的电影,并且可以通过搜索电影名称来搜索和显示它们。 So I'm using the localStorage to store the data and then display when the search result matches the movie name string.所以我使用localStorage来存储数据,然后在搜索结果与电影名称字符串匹配时显示。 On 'submit' of a button I can see the localStorage has the data but the data is not stored permanently.在按钮的“提交”上,我可以看到 localStorage 有数据,但数据不是永久存储的。 It just gets removed when I tried to enter the next input.当我尝试输入下一个输入时,它会被删除。 So how can I resolve the issue and what are the best ways to store data efficiently.那么我该如何解决这个问题以及有效存储数据的最佳方法是什么。

<! Start of the snippet -->

        import React from 'react';
        import './App.css';
        import Search from './components/Search';
        import FormInput from './components/FormInput';
        import Show from './components/Show';
        import {Container, Row, Col} from 'react-bootstrap';


        class App extends React.Component {

          userData;
          state = {
            
              movieName: '',
              ratings: '',
              duration: ''
            
          }

          

          handleMovieName = (e) =>{
            this.setState({movieName: e.target.value})
          }
          handleRatings = (e) => {
            this.setState({ratings: e.target.value})
          }
          handleDuration = (e) => {
            this.setState({duration: e.target.value})
          }
          handleSubmit = (e) => {
            console.log(`${this.state.movieName} ${this.state.ratings} ${this.state.duration}`);
            e.preventDefault();
          componentDidMount(){
            this.userData = JSON.parse(localStorage.getItem('user'));

            if(localStorage.getItem('user')){
              this.setState({
                movieName: this.userData.movieName,
                ratings: this.userData.ratings,
                duration: this.userData.duration
              })
            } else{
              this.setState({
                movieName: '',
                ratings: '',
                duration: ''
              })
            }
          }

          componentWillUpdate(nextProps, nextState){
            localStorage.setItem('movieName', JSON.stringify(nextState));
          }

        render() {
          return (
            <div>
              <header><h1>Netflix Movie Directory</h1></header>

                <main>
                <Search />
                <Container className="container1">
                  <Row noGutters="true">
                    <Col xs={12} md={8}>
                      <Show 
                        handleDuration = {this.state.duration}
                        handleRatings = {this.state.ratings}
                        handleMovieName = {this.state.movieName} />
                    </Col>
                    <Col xs={6} md={4}>
                      <FormInput 
                        handleSubmit={this.handleSubmit} 
                        handleDuration = {this.handleDuration}
                        handleRatings = {this.handleRatings}
                        handleMovieName = {this.handleMovieName} />
                    </Col>
                  </Row>
                </Container>
          
                </main>
            </div>
          );
         }
        }

        export default App;


    <!-- end snippet --> 

It seems very likely that the bug comes from a mismatch in localStorage keys.该错误很可能来自 localStorage 键的不匹配。

You never set user key in localStorage but if it is not present, you reset component's state which triggers componentWillUpdate which will re-write info stored in local storage under movieName key.永远不会在 localStorage 中设置user键,但如果它不存在,您将重置组件的状态,触发componentWillUpdate ,这将重写存储在本地存储中的movieName键下的movieName
So, probably you want to read movieName instead of user from local storage like this:因此,您可能想从本地存储中读取movieName而不是user ,如下所示:

componentDidMount(){
  const maybeMovieInfo = JSON.parse(localStorage.getItem('movieName'));

  if(localStorage.getItem('movieName')){
    this.setState({
      movieName: maybeMovieInfo.movieName,
      ratings: maybeMovieInfo.ratings,
      duration: maybeMovieInfo.duration
    })
  } else{
    this.setState({
      movieName: '',
      ratings: '',
      duration: ''
    })
  }
}

Generally speaking, storing information of this type in local storage is a perfectly valid use case.一般来说,在本地存储中存储这种类型的信息是一个非常有效的用例。

I wonder why you need to use componentWillUpdate.我想知道为什么您需要使用 componentWillUpdate。 It is marked as unsafe so try to avoid it.它被标记为不安全,所以尽量避免它。 It is mentioned clearly in the docs: https://reactjs.org/docs/react-component.html#updating So I suggest to remove this:它在文档中明确提到: https : //reactjs.org/docs/react-component.html#updating所以我建议删除它:

componentWillUpdate(nextProps, nextState){
            localStorage.setItem('movieName', JSON.stringify(nextState));
          }

instead do the store update logic in your handleSubmit而是在您的 handleSubmit 中执行商店更新逻辑

handleSubmit = (e) => {
            console.log(`${this.state.movieName} ${this.state.ratings} ${this.state.duration}`);
            localStorage.setItem('movieName', JSON.stringify(nextState));

        e.preventDefault();}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 存储图像然后显示它们的最佳方法 - best way to store images and then display them 一种在React中使用localstorage显示组件一次的方法 - A way to display the component once by using localstorage in React 如何在 React 应用启动时检索 localStorage 数据并使用 useEffect 将其存储在 Redux 中? (它一直在清除我的数据) - How do I retrieve localStorage data on React app start and store it in Redux using useEffect? (It keeps wiping out my data) 如何将标签存储在数组中并使用 React 显示它们? - How can you store labels in an array and display them using React? 在localstorage中保存javascript数据的最佳方式 - Best way to save javascript data in localstorage 在反应应用程序上存储资产/内容的最佳方式是什么? - What is the best way to store assets/content on a react app? 从Windows 8 Store应用程序本地存储中提取数据 - Extract data from Windows 8 Store app localstorage 如何在 Angular 8 中存储像 jwt 令牌这样的数据? 是否有另一种使用本地存储或会话存储安全存储的方法? - How to store data like jwt token in Angular 8? Is there another way to store safely using localstorage or session storage? 使用带有自定义钩子 React 的 localStorage 存储编号 - Store number using localStorage with custom hook React 在private-native中存储私有数据的最佳方法是什么? - What is the best way to store private data in react-native?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM