React document.addEventListener正在检测多个按键

时间:2018-09-03 14:36:52

标签: javascript reactjs

我正在尝试为我的React Js计算器应用程序创建一个按键监听器,当我添加事件监听器时,它会检测到我按得越多的其他按键。有没有更好的放置事件监听器的地方?当我按1234时,我得到

  

122333344444444

 /****************Button Component*************/
class CalcApp extends React.Component {

state = {
  value: null,
  displayNumbers: '0',
  selectedNumbers: [],
  calculating: false,
  operator:null
 };



selectMath = (selectedMath) =>{
const {displayNumbers, operator,value} = this.state;
const nextValue = parseFloat(displayNumbers)
console.log(selectedMath);

 /**do math and other methods*/

render() {
document.addEventListener('keydown', (event) => {
    const keyName = event.key;
  if(/^\d+$/.test(keyName)){
    this.selectButton(keyName)
    console.log(keyName);
    }
  });
return (
    <div>
        <Display displayNumbers={this.state.displayNumbers}
        selectedNumbers={this.state.selectedNumbers}/>
        <Button selectedNumbers={this.state.selectedNumbers}
                selectButton ={this.selectButton}
                selectC = {this.selectC}
                displayNumbers={this.state.displayNumbers}
                selectDot = {this.selectDot}
                selectMath = {this.selectMath}/>
    </div>
);
}
}

let domContainer = document.querySelector('#app');
ReactDOM.render(<CalcApp />, domContainer);

1 个答案:

答案 0 :(得分:1)

document.addEventListener移除render()侦听器。

每当需要重新渲染组件(更改state / props)时,都会调用该方法,该方法附加了另一个事件侦听器。

建议:将document.addEventListener移至componentDidMount()-仅执行一次,然后通过document.removeEventListener上的componentWillUnmount将其删除,以防止内存泄漏。< / p>