【发布时间】:2021-09-15 03:48:48
【问题描述】:
我去reactjs官网找到了这个
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
如果我要替换
componentDidMount() {
window.addEventListener('keydown', this.keypressed);
}
有了这个
useEffect(() => {
window.addEventListener('keydown', keypressed);
},[]);
这应该是个问题吧?
但是当我使用 useEffect 并快速按下键时,它会破坏基于类的组件中没有发生的站点。
这是我的基于类的组件代码,运行良好且不会破坏网站
/* eslint-disable eqeqeq */
import React, { Component } from 'react';
import data from './content/data';
import List from './List';
import Image from './Image';
import '../style/App.sass';
export class App extends Component {
state = {
currentIndex: 0,
};
componentDidMount() {
window.addEventListener('keydown', this.keypressed);
}
keypressed = (e) => {
let { currentIndex } = this.state;
if (e.keyCode == '38' || e.keyCode == '40') e.preventDefault();
if (e.keyCode == '38') {
this.setState({
currentIndex: (currentIndex - 1 + data.length) % data.length,
});
}
if (e.keyCode == '40') {
this.setState({
currentIndex: (currentIndex + 1) % data.length,
});
}
};
sendIndex = (i) =>
this.setState({
currentIndex: i,
});
render() {
return (
<div className="container0">
<List
currentIndex={this.state.currentIndex}
sendIndex={this.sendIndex}
/>
<Image currentIndex={this.state.currentIndex} />
</div>
);
}
}
export default App;
这是我的基于函数的组件代码
/* eslint-disable eqeqeq */
import React, { useState, useEffect } from 'react';
import data from './content/data';
import List from './List';
import Image from './Image';
import '../style/App.sass';
const App = () => {
const [currentIndex, setCurrentIndex] = useState(0);
const keypressed = (e) => {
if (e.keyCode == '38' || e.keyCode == '40') e.preventDefault();
if (e.keyCode == '38')
setCurrentIndex((currentIndex - 1 + data.length) % data.length);
if (e.keyCode == '40')
setCurrentIndex((currentIndex + 1) % data.length);
};
const sendIndex = (i) => setCurrentIndex(i);
// window.addEventListener('keydown', keypressed);
useEffect(() => {
window.addEventListener('keydown', keypressed);
}, []);
return (
<div className="container0">
<List currentIndex={currentIndex} sendIndex={sendIndex} />
<Image currentIndex={currentIndex} />
</div>
);
};
export default App;
请告诉我我做错了什么。
【问题讨论】:
-
您是否在浏览器的控制台中遇到任何错误?
-
@KundanSinghChouhan 不,我没有收到任何错误
标签: javascript html css reactjs react-native