【问题标题】:debounce on react got e.target.value undefined反跳反应得到 e.target.value 未定义
【发布时间】:2018-03-03 05:52:24
【问题描述】:

试图使用 lodash 的 debounce 对输入进行 debounce,但下面的代码给了我 undefined 的值。

const { debounce } from 'lodash'

class App extends Component {

  constructor(){
    super()
    this.handleSearch = debounce(this.handleSearch, 300)
  }

  handleSearch = e => console.log(e.target.value)

  render() {
    return <input onChange={e => this.handleSearch(e)} placeholder="Search" />
  }

}

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

这是因为 React 端的事件池。

SyntheticEvent 是池化的。这意味着 SyntheticEvent 对象将被重用,并且所有属性都将在 事件回调已被调用。这是出于性能原因。作为 因此,您不能以异步方式访问事件。

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

class App extends React.Component {

  constructor() {
    super()
    this.handleSearch = debounce(this.handleSearch, 2000);
  }

  handleSearch(event) {
    console.log(event.target.value);
  }

  render() {
    return <input onChange = {
      (event)=>{event.persist(); this.handleSearch(event)}
    }
    placeholder = "Search" / >
  }

}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

https://reactjs.org/docs/events.html#event-pooling

【讨论】:

  • 有道理,但它不能解决我的问题。我遇到了同样的错误。
  • e.target.value 是undefined
  • 奇怪你有什么改变吗?
  • @SharonChai onChange 处理程序。在 debounced 函数中调用 event.persist() 将不起作用。
  • 我现在得到一个 e.target.value 的空字符串。
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 1970-01-01
  • 2014-09-18
  • 2018-07-06
  • 1970-01-01
  • 2021-06-02
  • 2021-09-20
  • 2018-05-20
相关资源
最近更新 更多