Javascript 如何将本地存储添加到React.js应用程序?

Javascript 如何将本地存储添加到React.js应用程序?,javascript,reactjs,Javascript,Reactjs,我有一个应用程序待办事项列表,其中包含存储不同项目的注释,如列表项、注释、注释数等 你能帮我将localStorage添加到我的应用程序中,这样所有项目都可以保存到localStorage吗 我读过一篇文章说我们需要设置两个变量的路径:key和object。如何通过所有项目传递整个状态 代码如下: App.js import React, { Component } from 'react'; import './App.css'; import ListInput from './compon

我有一个应用程序待办事项列表,其中包含存储不同项目的注释,如列表项、注释、注释数等

你能帮我将localStorage添加到我的应用程序中,这样所有项目都可以保存到localStorage吗

我读过一篇文章说我们需要设置两个变量的路径:key和object。如何通过所有项目传递整个状态

代码如下:

App.js

import React, { Component } from 'react';
import './App.css';
import ListInput from './components/listInput'
import ListItem from './components/listItem'
import SideBar from './components/sideBar'
import CommentsSection from './components/commentsSection'

class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      items: [
        {
          id: 1, 
          title: 'First item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
        {
          id: 2, 
          title: 'Second item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
        {
          id: 3, 
          title: 'Third item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
      ],
      activeItem: {},
      isHidden: true
    }
  }
  // Add new item to the list
  addItem = inputText => {
    let itemsCopy = this.state.items.slice();
    itemsCopy.push({id: this.state.items.length + 1, title: inputText, commentsCount: 0, comments: [], displayComment: false});

    this.setState({
      items: itemsCopy,
    })
  }
  // Remove the item from the list: check if the clicked button id is match 
  removeItem = id =>
    this.setState({
      items: this.state.items.filter((item, index) => item.id !== id)
    })

  addComment = (inputComment) => {
    // find item with id passed and select its comments array
     const commentCopy = this.state.items.map(item => {
       if (item.id === this.state.activeItem.id) {
         return {
           ...item, 
           commentsCount: item.comments.length + 1,
           comments: item.comments.concat({id: item.comments.length + 1, text: inputComment})
          } 
       }
         return item
      });
      this.setState({
       items: commentCopy
     })
   }

  getActiveItem = () => this.state.items.find(item => item.id === this.state.activeItem.id)

  render() {
    console.log(this.state.items.isHidden)
    return (
      <div className='App'>
        <SideBar />
        <div className='flex-container'>
          <div className='list-wrapper'>
            <h1>Items</h1>
            <ListInput inputText='' addItem={this.addItem}/>
            <ul>
              {
                this.state.items.map((item) => 
                (<ListItem 
                    item={item} 
                    key={item.id} 
                    id={item.id} 
                    removeItem={this.removeItem} 
                    setActiveComment={() => this.setState({ activeItem: item })} 
                    toggleHidden={() => this.setState({ isHidden: false })}
                  />
                ))
              }
            </ul>
          </div>
          <div>
            {!this.state.isHidden && <CommentsSection 
              addComment={this.addComment} 
              activeItem={this.getActiveItem()}
            />}
          </div>  
        </div>  
      </div>
    );
  }
}
export default App;
import React from 'react';
import CommentInput from './commentInput'
import CommentsItem from './commentsItem'
import './commentsSection.css';

export default class CommentsSection extends React.Component {
    constructor(props){
        super(props);
        this.state = {value: ''};
    }

    handleChange = event => this.setState({value: event.target.value})

    handleEnter = event => {
        if (event.charCode === 13 && event.ctrlKey) {
            console.log(this.state, this.props)
            this.addComment(this.state.value)
        } 
    }    

    addComment = comment => {
        console.log(this.props.activeComment)
         // Ensure the comment text isn't empty
        if (comment.length > 0) {
          this.props.addComment(comment);
          this.setState({value: ''});
        }   
    }

    render() {
        return (
            <div className='component-section'>
                <h1>{this.props.activeItem && this.props.activeItem.title}</h1>
                <ul>
                { this.props.activeItem &&
                    this.props.activeItem.comments.map((comment) => <p key={comment.id}>{comment.text}</p>)
                }
                </ul>
                {/*<CommentsItem />*/}
                {/*<CommentInput addComment={this.addComment}/>*/}
                <div className='comment-input'>
                    <input type='text' value={this.state.value} onChange={this.handleChange} onKeyPress={this.handleEnter}/>
                </div>
            </div>
        )
    }
}
import React from 'react';
import './listInput.css'

export default class ListInput extends React.Component {
    constructor(props){
        super(props);
        this.state = {value: this.props.inputText};

        this.handleChange = this.handleChange.bind(this);
        this.addItem = this.addItem.bind(this);
    }

    handleChange = event => this.setState({value: event.target.value})

    addItem(item) {
        // Ensure the todo text isn't empty
        if (item.length > 0) {
          this.props.addItem(item);
          this.setState({value: ''});
        }   
    }

    render() {
      return (
        <div className='list-input'>
            <input type='text' value={this.state.value} onChange={this.handleChange} placeholder={'Type name here...'}/>
            <button className='btn btn-primary' onClick={() => this.addItem(this.state.value)}>Add new</button>
        </div>
      )
    }
  }
import React,{Component}来自'React';
导入“/App.css”;
从“./components/ListInput”导入ListInput
从“./components/ListItem”导入ListItem
从“./components/SideBar”导入侧栏
从“./components/CommentsSection”导入CommentsSection
类应用程序扩展组件{
建造师(道具){
超级(道具);
此.state={
项目:[
{
id:1,
标题:“第一项”,
评论:0,
评论:[],
displayComment:false
},
{
id:2,
标题:“第二项”,
评论:0,
评论:[],
displayComment:false
},
{
id:3,
标题:"第三项",,
评论:0,
评论:[],
displayComment:false
},
],
活动项:{},
伊希登:是的
}
}
//将新项目添加到列表中
addItem=inputText=>{
让itemsCopy=this.state.items.slice();
push({id:this.state.items.length+1,title:inputText,commentsCount:0,comments:[],displayComment:false});
这是我的国家({
项目:项目,,
})
}
//从列表中删除项目:检查单击的按钮id是否匹配
removietem=id=>
这是我的国家({
items:this.state.items.filter((项,索引)=>item.id!==id)
})
addComment=(inputComment)=>{
//查找传递了id的项并选择其注释数组
const commentCopy=this.state.items.map(item=>{
if(item.id==this.state.activeItem.id){
返回{
…项目,
commentsCount:item.comments.length+1,
注释:item.comments.concat({id:item.comments.length+1,text:inputComment})
} 
}
退货项目
});
这是我的国家({
项目:评论副本
})
}
getActiveItem=()=>this.state.items.find(item=>item.id===this.state.activeItem.id)
render(){
console.log(this.state.items.ishiden)
返回(
项目
    { this.state.items.map((item)=> (this.setState({activeItem:item})} toggleHidden={()=>this.setState({isHidden:false}) /> )) }
{!this.state.ishiden&} ); } } 导出默认应用程序;
commentSection.js

import React, { Component } from 'react';
import './App.css';
import ListInput from './components/listInput'
import ListItem from './components/listItem'
import SideBar from './components/sideBar'
import CommentsSection from './components/commentsSection'

class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      items: [
        {
          id: 1, 
          title: 'First item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
        {
          id: 2, 
          title: 'Second item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
        {
          id: 3, 
          title: 'Third item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
      ],
      activeItem: {},
      isHidden: true
    }
  }
  // Add new item to the list
  addItem = inputText => {
    let itemsCopy = this.state.items.slice();
    itemsCopy.push({id: this.state.items.length + 1, title: inputText, commentsCount: 0, comments: [], displayComment: false});

    this.setState({
      items: itemsCopy,
    })
  }
  // Remove the item from the list: check if the clicked button id is match 
  removeItem = id =>
    this.setState({
      items: this.state.items.filter((item, index) => item.id !== id)
    })

  addComment = (inputComment) => {
    // find item with id passed and select its comments array
     const commentCopy = this.state.items.map(item => {
       if (item.id === this.state.activeItem.id) {
         return {
           ...item, 
           commentsCount: item.comments.length + 1,
           comments: item.comments.concat({id: item.comments.length + 1, text: inputComment})
          } 
       }
         return item
      });
      this.setState({
       items: commentCopy
     })
   }

  getActiveItem = () => this.state.items.find(item => item.id === this.state.activeItem.id)

  render() {
    console.log(this.state.items.isHidden)
    return (
      <div className='App'>
        <SideBar />
        <div className='flex-container'>
          <div className='list-wrapper'>
            <h1>Items</h1>
            <ListInput inputText='' addItem={this.addItem}/>
            <ul>
              {
                this.state.items.map((item) => 
                (<ListItem 
                    item={item} 
                    key={item.id} 
                    id={item.id} 
                    removeItem={this.removeItem} 
                    setActiveComment={() => this.setState({ activeItem: item })} 
                    toggleHidden={() => this.setState({ isHidden: false })}
                  />
                ))
              }
            </ul>
          </div>
          <div>
            {!this.state.isHidden && <CommentsSection 
              addComment={this.addComment} 
              activeItem={this.getActiveItem()}
            />}
          </div>  
        </div>  
      </div>
    );
  }
}
export default App;
import React from 'react';
import CommentInput from './commentInput'
import CommentsItem from './commentsItem'
import './commentsSection.css';

export default class CommentsSection extends React.Component {
    constructor(props){
        super(props);
        this.state = {value: ''};
    }

    handleChange = event => this.setState({value: event.target.value})

    handleEnter = event => {
        if (event.charCode === 13 && event.ctrlKey) {
            console.log(this.state, this.props)
            this.addComment(this.state.value)
        } 
    }    

    addComment = comment => {
        console.log(this.props.activeComment)
         // Ensure the comment text isn't empty
        if (comment.length > 0) {
          this.props.addComment(comment);
          this.setState({value: ''});
        }   
    }

    render() {
        return (
            <div className='component-section'>
                <h1>{this.props.activeItem && this.props.activeItem.title}</h1>
                <ul>
                { this.props.activeItem &&
                    this.props.activeItem.comments.map((comment) => <p key={comment.id}>{comment.text}</p>)
                }
                </ul>
                {/*<CommentsItem />*/}
                {/*<CommentInput addComment={this.addComment}/>*/}
                <div className='comment-input'>
                    <input type='text' value={this.state.value} onChange={this.handleChange} onKeyPress={this.handleEnter}/>
                </div>
            </div>
        )
    }
}
import React from 'react';
import './listInput.css'

export default class ListInput extends React.Component {
    constructor(props){
        super(props);
        this.state = {value: this.props.inputText};

        this.handleChange = this.handleChange.bind(this);
        this.addItem = this.addItem.bind(this);
    }

    handleChange = event => this.setState({value: event.target.value})

    addItem(item) {
        // Ensure the todo text isn't empty
        if (item.length > 0) {
          this.props.addItem(item);
          this.setState({value: ''});
        }   
    }

    render() {
      return (
        <div className='list-input'>
            <input type='text' value={this.state.value} onChange={this.handleChange} placeholder={'Type name here...'}/>
            <button className='btn btn-primary' onClick={() => this.addItem(this.state.value)}>Add new</button>
        </div>
      )
    }
  }
从“React”导入React;
从“/CommentInput”导入CommentInput
从“/CommentsItem”导入CommentsItem
导入“/commentsSection.css”;
导出默认类CommentsSection扩展React.Component{
建造师(道具){
超级(道具);
this.state={value:''};
}
handleChange=event=>this.setState({value:event.target.value})
HandleCenter=事件=>{
if(event.charCode==13&&event.ctrlKey){
console.log(this.state、this.props)
this.addComment(this.state.value)
} 
}    
addComment=comment=>{
log(this.props.activeComment)
//确保注释文本不是空的
如果(comment.length>0){
this.props.addComment(comment);
this.setState({value:'});
}   
}
render(){
返回(
{this.props.activeItem&&this.props.activeItem.title}
    {this.props.activeItem&& this.props.activeItem.comments.map((comment)=>

    {comment.text}

    ) }
{/**/} {/**/} ) } }
listInput.js

import React, { Component } from 'react';
import './App.css';
import ListInput from './components/listInput'
import ListItem from './components/listItem'
import SideBar from './components/sideBar'
import CommentsSection from './components/commentsSection'

class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      items: [
        {
          id: 1, 
          title: 'First item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
        {
          id: 2, 
          title: 'Second item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
        {
          id: 3, 
          title: 'Third item',
          commentsCount: 0,
          comments: [],
          displayComment: false
        },
      ],
      activeItem: {},
      isHidden: true
    }
  }
  // Add new item to the list
  addItem = inputText => {
    let itemsCopy = this.state.items.slice();
    itemsCopy.push({id: this.state.items.length + 1, title: inputText, commentsCount: 0, comments: [], displayComment: false});

    this.setState({
      items: itemsCopy,
    })
  }
  // Remove the item from the list: check if the clicked button id is match 
  removeItem = id =>
    this.setState({
      items: this.state.items.filter((item, index) => item.id !== id)
    })

  addComment = (inputComment) => {
    // find item with id passed and select its comments array
     const commentCopy = this.state.items.map(item => {
       if (item.id === this.state.activeItem.id) {
         return {
           ...item, 
           commentsCount: item.comments.length + 1,
           comments: item.comments.concat({id: item.comments.length + 1, text: inputComment})
          } 
       }
         return item
      });
      this.setState({
       items: commentCopy
     })
   }

  getActiveItem = () => this.state.items.find(item => item.id === this.state.activeItem.id)

  render() {
    console.log(this.state.items.isHidden)
    return (
      <div className='App'>
        <SideBar />
        <div className='flex-container'>
          <div className='list-wrapper'>
            <h1>Items</h1>
            <ListInput inputText='' addItem={this.addItem}/>
            <ul>
              {
                this.state.items.map((item) => 
                (<ListItem 
                    item={item} 
                    key={item.id} 
                    id={item.id} 
                    removeItem={this.removeItem} 
                    setActiveComment={() => this.setState({ activeItem: item })} 
                    toggleHidden={() => this.setState({ isHidden: false })}
                  />
                ))
              }
            </ul>
          </div>
          <div>
            {!this.state.isHidden && <CommentsSection 
              addComment={this.addComment} 
              activeItem={this.getActiveItem()}
            />}
          </div>  
        </div>  
      </div>
    );
  }
}
export default App;
import React from 'react';
import CommentInput from './commentInput'
import CommentsItem from './commentsItem'
import './commentsSection.css';

export default class CommentsSection extends React.Component {
    constructor(props){
        super(props);
        this.state = {value: ''};
    }

    handleChange = event => this.setState({value: event.target.value})

    handleEnter = event => {
        if (event.charCode === 13 && event.ctrlKey) {
            console.log(this.state, this.props)
            this.addComment(this.state.value)
        } 
    }    

    addComment = comment => {
        console.log(this.props.activeComment)
         // Ensure the comment text isn't empty
        if (comment.length > 0) {
          this.props.addComment(comment);
          this.setState({value: ''});
        }   
    }

    render() {
        return (
            <div className='component-section'>
                <h1>{this.props.activeItem && this.props.activeItem.title}</h1>
                <ul>
                { this.props.activeItem &&
                    this.props.activeItem.comments.map((comment) => <p key={comment.id}>{comment.text}</p>)
                }
                </ul>
                {/*<CommentsItem />*/}
                {/*<CommentInput addComment={this.addComment}/>*/}
                <div className='comment-input'>
                    <input type='text' value={this.state.value} onChange={this.handleChange} onKeyPress={this.handleEnter}/>
                </div>
            </div>
        )
    }
}
import React from 'react';
import './listInput.css'

export default class ListInput extends React.Component {
    constructor(props){
        super(props);
        this.state = {value: this.props.inputText};

        this.handleChange = this.handleChange.bind(this);
        this.addItem = this.addItem.bind(this);
    }

    handleChange = event => this.setState({value: event.target.value})

    addItem(item) {
        // Ensure the todo text isn't empty
        if (item.length > 0) {
          this.props.addItem(item);
          this.setState({value: ''});
        }   
    }

    render() {
      return (
        <div className='list-input'>
            <input type='text' value={this.state.value} onChange={this.handleChange} placeholder={'Type name here...'}/>
            <button className='btn btn-primary' onClick={() => this.addItem(this.state.value)}>Add new</button>
        </div>
      )
    }
  }
从“React”导入React;
导入“./listInput.css”
导出默认类ListInput扩展React.Component{
建造师(道具){
超级(道具);
this.state={value:this.props.inputText};
this.handleChange=this.handleChange.bind(this);
this.addItem=this.addItem.bind(this);
}
handleChange=event=>this.setState({value:event.target.value})
附加项(项目){
//确保待办事项文本不是空的
如果(item.length>0){
本.道具.附件(项目);
this.setState({value:'});
}   
}
render(){
返回(
this.addItem(this.state.value)}>addnew
)
}
}

React使操作变得非常简单

// setter
localStorage.setItem('myData', data);

// getter
localStorage.getItem('myData');

您可以通过浏览器自动访问
localStorage
对象。请记住,
.setItem
没有返回值,所以只需同步使用它。

React使其非常简单

// setter
localStorage.setItem('myData', data);

// getter
localStorage.getItem('myData');
您可以通过浏览器自动访问
localStorage
对象。请记住,
.setItem
没有返回值,所以只需同步使用它。

一个简单的解释: localStorage有两种重要的方法:

  • localStorage.setItem(*名称*,*字符串值*)

    • 参数
      name
      只是希望存储在存储器中以方便引用数据的键
    • 参数
      字符串值
      只是希望存储在
      键/name
      下的值。重要的是