2017-09-06 6 views
0

입력 필드를 사용하여 기본 javascript localstorage api (또는 npm의 모든 로컬 로컬 저장 모듈)를 사용하여 로컬 저장소에 저장하려고하지만 마지막으로 입력 한 문자에서 최소 5 초 간격으로 로컬 저장소에 저장하는 코드를 구현하는 데 약간의 문제가 있습니다.이벤트 누적없이 일정 시간 만 클릭하면 실행

import React, { Component } from 'react'; 
import throttle from 'lodash/throttle'; 

class Something extends Component { 
    state = { inputValue: "" }; 

    handleChange =() => { 
    this.changeState(); 
    } 

    changeState = throttle(
    newValue => { 
     this.setState({ inputValue: newValue }); 
     console.log('executed!'); 
    }, 
    5000 
); 

    render() { 
    return (
     <div> 
     <input type="text" 
      value={this.state.inputValue} 
      placeholder="Type something here" 
      onChange={this.handleChange} 
     /> 
     </div> 
    ); 
    } 
}; 

문제는 방법 changeState()가 성공적으로 오초 후에 실행하지만 그것은 당신이 그것을 스팸 얼마나 많은 클릭을 기반으로 한 번에 다시 실행됩니다 있다는 것입니다. 저것을 막는 방법은 무엇입니까?

+0

실행 여부를 추적하는 모듈 변수를 설정할 수 있습니까? 예 : 실행 = false; false로 설정된 경우 changeState 핸들러의 코드 만 실행합니까? 분명히 실행되면 true로 설정하십시오. 어쩌면 더 좋은 방법으로 네이티브 반응을 보일 수 있습니다. 전혀 신경 쓰지 않고받은 답변이 상당히 합리적입니다.

답변

3

당신은 debounce하고 싶습니다. 함수를 디 바운스 할 경우 마지막으로 호출 된 후 특정 시간만큼만 함수가 실행됩니다. 다시 호출되면 타이머가 실행되기 전에 재설정됩니다. Lodash에는 debounce 방법이 있습니다. save 메소드를 5000ms 씩 디 바운딩 한 다음 사용자가 입력을 변경할 때마다 함수를 호출하고 5 초 동안 입력을 중지하면 저장이 호출됩니다. 여기에 로다시 ​​디 바운스 문서가 있습니다 https://lodash.com/docs/4.17.4#debounce

1

로다시 debounce()을 사용할 수 있습니다.

1

간격을 componentDidMount로 이동하고 this.state.inputValue을 로컬 저장소에 저장하십시오. onChange 그냥 상태 값을 설정합니다.

import React, { Component } from 'react'; 
import throttle from 'lodash/throttle'; 

class Something extends Component { 
    state = { inputValue: "", changed: false }; 

    handleChange = (event) => { 
    this.setState({ inputValue: event.target.value, changed: true }); 
    } 

    componentDidMount() { 
     this.interval = setInterval(()=> { 
      if (this.state.changed === true) { 
       // here save to the localStorage this.state.inputValue 
       this.setState({ changed: false }); 
      } 
     }, 5000); 
    } 

    componentWillUnmount() { 
     clearInterval(this.interval); 
    } 

    render() { 
    return (
     <div> 
     <input type="text" 
      value={this.state.inputValue} 
      placeholder="Type something here" 
      onChange={this.handleChange} 
     /> 
     </div> 
    ); 
    } 
};