React和LocalStorage重复数据问题

时间:2019-01-03 10:49:28

标签: reactjs local-storage

简而言之,我添加了一个输入和一个提交按钮。如果我在noteTitle输入中添加一些字符串,那么我会将其列出在标记内。

但是当我单击按钮时,它会添加重复项。

例如:

输入-> ADAM 点击

打印:ADAM

和:

输入-> MIKE 点击

打印:ADAM,ADAM,MIKE

如果刷新页面,一切都很好。

那么您如何看待问题所在?

import React, { Component } from 'react';

export default class NoteAdd extends Component {

constructor(props) {
super(props);
console.log("Konsol:", localStorage.getItem("state"));  
}

state = {
  id : 0,
  noteList : [],
  noteTitle : ""
}     

onChangeTitle = (e) => {
this.setState({
    noteTitle : e.target.value
});   
}

onSubmitForm = (e) => {
let {id, noteList, noteTitle} = this.state; 
e.preventDefault();
this.setState((prevState) => ({
  id: prevState.id + 1
})); 

if(localStorage.getItem("state") !== null) {
  noteList.push({
    id : id,
    noteTitle : localStorage.getItem("state")  
  });
}

 noteList.push({
  id : id,
  noteTitle : noteTitle   
 });

localStorage.setItem("state", 
  noteList.map(user => {
    return (
      user.noteTitle
    )
  })
 ); 
} 

render(){
 const {noteTitle, noteContent} = this.state;  

return (
  <div>
      <form>
        <div className="noteTitle"><h5>Not başlığı :</h5> <input value={noteTitle} onChange={this.onChangeTitle} type="text" /></div>
        <input className="noteSubmitBtn" type="submit" onClick={this.onSubmitForm} value="Notu Ekle"/>
        <span id="kayit">{localStorage.getItem("state")}</span>
      </form>
      {/* <NoteList noteList={this.state.noteList} /> */}
  </div>
) 
}

}

1 个答案:

答案 0 :(得分:1)

onChange功能上,您正在将状态设置为键盘输入:

onChangeTitle = (e) => {
this.setState({
    noteTitle : e.target.value
});   
}

现在,当您记录第一个状态时,您的状态是:

this.state.noteTitle = 'ADAM';

现在您键入mike,然后状态变为:

this.state.noteTitle = 'ADAMMIKE';

在提交这样的值后,您需要清除状态,以便在键入新名称时,它应该以0开头。

onSubmitForm = (e) => {
let {id, noteList, noteTitle} = this.state; 
e.preventDefault();
this.setState((prevState) => ({
  id: prevState.id + 1
})); 

if(localStorage.getItem("state") !== null) {
  noteList.push({
    id : id,
    noteTitle : localStorage.getItem("state")  
  });
}

 noteList.push({
  id : id,
  noteTitle : noteTitle   
 });

localStorage.setItem("state", 
  noteList.map(user => {
    return (
      user.noteTitle
    )
  })
 );
this.setState({noteTitle: '', noteContent: ''}) // Here you need to reset the state to it's initial value.

}