有没有可能的方法,通过映射数组并从功能组件到类组件使用“ useEffect”来重写代码?

时间:2020-01-26 18:22:47

标签: arrays reactjs sorting mapping

我使用我的Logs组件来映射对象数组中的日志。我的问题是,使用“ useEffect”会使我的应用程序运行缓慢。有什么办法可以将其重写为类组件?

我的代码:

import React, { useEffect } from "react";
import Log from "../logs/log";
import "../../scss/logs.scss";
const Logs = ({ logs, changeDetailState, getLogId, onClick, mountLogs }) => {
  useEffect(() => {
    mountLogs();
  });
  const logsmap = logs.map((log, i) => (
    <Log
      onClick={onClick}
      getLogId={getLogId}
      changeDetailState={changeDetailState}
      key={i}
      input={log.amount}
      description={log.description}
      id={i}
    />
  ));
  return <div className="logs">{logsmap}</div>;
};
export default Logs;

2 个答案:

答案 0 :(得分:0)

每次属性更改时,您都在调用mountLogs()。

如果您希望它在挂载后仅运行一次,请使用:

  useEffect(() => {
    mountLogs();
  }, []);

如果要对特定值进行更改,则应使用:

  useEffect(() => {
    mountLogs();
  }, [logs, changeDetailState]);

要运行一次,应按以下方式使用它:

import React, { useEffect } from "react";
import Log from "../logs/log";
import "../../scss/logs.scss";
const Logs = ({ logs, changeDetailState, getLogId, onClick, mountLogs }) => {
  useEffect(() => {
    mountLogs();
  }, []);
  const logsmap = logs.map((log, i) => (
    <Log
      onClick={onClick}
      getLogId={getLogId}
      changeDetailState={changeDetailState}
      key={i}
      input={log.amount}
      description={log.description}
      id={i}
    />
  ));
  return <div className="logs">{logsmap}</div>;
};
export default Logs;

答案 1 :(得分:0)

您可以通过执行以下操作将其转换为Class Component

class Logs extends React.Component {
    componentDidMount() {
        const { mountLogs } = this.props;

        mountLogs();
    }
}

processLogsMap = () => {
    const { logs } = this.props;
    logs.map((log, i) => (
    <Log
      onClick={onClick}
      getLogId={getLogId}
      changeDetailState={changeDetailState}
      key={i}
      input={log.amount}
      description={log.description}
      id={i}
    />
  ));
}

render() {
    return (
        <>
            <div className="logs">{processLogsMap()}</div>; 
        </>
    )
}

export default Logs;