【问题标题】:How to replace class-based components with hooks in reactreact中如何用钩子替换基于类的组件
【发布时间】: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


【解决方案1】:

由于未知原因,您禁用了 eslint 错误 (/* eslint-disable */),建议您使用它们修复关闭 currentIndex 状态的陈旧值。

可能的解决方法是将回调传递给useState setter:

const App = () => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const sendIndex = (i) => setCurrentIndex(i);

  useEffect(() => {
    const keypressed = (e) => {
      if (e.keyCode == "38" || e.keyCode == "40") e.preventDefault();

      if (e.keyCode == "38")
        setCurrentIndex(
          (prevIndex) => (prevIndex - 1 + data.length) % data.length
        );

      if (e.keyCode == "40")
        setCurrentIndex((prevIndex) => (prevIndex + 1) % data.length);
    };
    window.addEventListener("keydown", keypressed);
  }, []);

  return (
    <div className="container0">
      <List currentIndex={currentIndex} sendIndex={sendIndex} />
      <Image currentIndex={currentIndex} />
    </div>
  );
};

【讨论】:

    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 2021-02-05
    • 2020-09-24
    • 2019-09-21
    • 1970-01-01
    • 2022-01-22
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多