【发布时间】:2015-11-04 15:12:42
【问题描述】:
我使用onChange 触发对elasticsearch 的API 调用,以便提示自动完成列表。
为了确保我的商店在重新渲染之前更新,我添加了 componentDidMount ,这样我就不会落后了。但切入正题需要代码,所以:
constructor(props) {
super(props)
this.state = {
inputValue: '',
options: []
};
this.props = {
inputValue: '',
options: []
};
this._onChange = this._onChange.bind(this);
}
componentDidMount() {
CodeStore.addChangeListener(this._onChange);
}
_onChange(event) {
if (this.state.inputValue && !event) {
var enteredChars = this.state.inputValue;
console.log('NO EVENT!');
} else if (event.target.value) {
console.log('EVENT!');
var enteredChars = event.target.value;
this.setState({inputValue: enteredChars});
}
CodeService.nextCode(enteredChars);
}
如您所见,我添加了一些日志事件只是为了确保我的状况正常。我读到setState 会引发重新渲染,因此它在条件内,但并没有停止循环。并且控制台日志确认条件切换。但是在我的条件中包含setState 会阻止功能并且我没有得到列表。
这是我的日志:
0
Home.jsx:48 EVENT!
Home.jsx:50 0
CodeService.js:27 request
CodeActions.js:10 dispatch
CodeStore.js:22 store
Home.jsx:43 1
Home.jsx:46 NO EVENT!
10OptionTemplate.jsx:15 render-list
CodeService.js:27 request
CodeActions.js:10 dispatch
CodeStore.js:22 store
Home.jsx:43 1
Home.jsx:46 NO EVENT!
10OptionTemplate.jsx:15 render-list
CodeService.js:27 request
CodeActions.js:10 dispatch
CodeStore.js:22 store
Home.jsx:43 1
Home.jsx:46 NO EVENT!
无论如何,无限循环不会损害性能。我认为是因为componentWillUnmount,但必须避免大量的 API 调用。希望这些信息足以作为任何证据。
【问题讨论】:
标签: javascript reactjs infinite-loop