首页 > 解决方案 > React 组件加载不停

问题描述

我的 React 组件无限加载,我希望它仅根据我从数据库中获取的数据加载,console.log("1")仅用于测试组件加载的次数。

这是组件:

import React from "react";
import Axios from "axios";
import { useState, useEffect } from "react";

function Added() {
  const [data, setData] = useState([]);

  useEffect(() => {
    Axios.get("http://localhost:3001/").then((result) => {
      setData(result.data);
    });
  }, [data]);

  console.log("1");

  return data.map((item) => {
    return (
      <div key={item._id}>
        <h1>{item.finame}</h1>
        <h1>{item.laname}</h1>
        <h5>{item.age}</h5>
      </div>
    );
  });
}

export default Added;

这是它加载的地方:

import "./App.css";
import { useState, useReducer, useEffect } from "react";
import Added from "./added";
import Axios from "axios";

function App() {
  const GettingALlTheData = () => {
    return Axios.get("http://localhost:3001/").then((result) => {
      return result.data;
    });
  };

  /* -------------------- For the useReducer -------------------- */
  const Actions = {
    Add: "add",
  };

  const defaultState = {
    list: [GettingALlTheData],
  };
  console.log(defaultState);

  const reducer = (state, action) => {
    switch (action.type) {
      case Actions.Add:
        const listItem = action.payload;
        try {
          Axios.post("http://localhost:3001/add", listItem);
        } catch (error) {
          console.log(error + "444444");
        }
        return { ...state, list: [...state.list, listItem] };

      default:
        console.log("this is the default");
    }
  };

  const [state, dispatch] = useReducer(reducer, defaultState);

  /* ---------------------------- For the form ---------------------------- */
  const [listItem, setListItem] = useState({ finame: "", laname: "", age: 0 });
  const [list, setList] = useState([]);

  useEffect(() => {
    Axios.get("http://localhost:3001/").then((result) => {
      state.list = result.data;
    });
  }, [state.list]);

  const handelChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;

    setListItem({ ...listItem, [name]: value });
  };

  const handelSubmit = (e) => {
    e.preventDefault();

    dispatch({ type: Actions.Add, payload: listItem });
  };

  const [data, setData] = useState({});

  /* -------- for the useEffect to get the Data from the server -------- */
  /* ------------------------ for the form return ---------------------- */
  return (
    <div className="App">
      <h1>CRUD app using MERN stack</h1>

      <form onSubmit={handelSubmit}>
        <label htmlFor="finame">First name:</label>
        <input
          type="text"
          name="finame"
          id="finame"
          value={listItem.finame}
          onChange={handelChange}
        />

        <label htmlFor="laname">Last name:</label>
        <input
          type="text"
          name="laname"
          id="laname"
          value={listItem.laname}
          onChange={handelChange}
        />

        <label htmlFor="age">Age:</label>
        <input
          type="Number"
          name="age"
          id="age"
          value={listItem.age}
          onChange={handelChange}
        />

        <button type="Submit">Submit</button>
      </form>

      {state.list ? (
        <Added />
      ) : (
        state.list.map((listItem) => {
          return (
            <div key={listItem._id}>
              <h1>First name : {listItem.finame}</h1>
              <h1>Last name: {listItem.laname}</h1>
              <h3>Age: {listItem.age}</h3>
            </div>
          );
        })
      )}
    </div>
  );
}

export default App;

标签: reactjscomponentsuse-effect

解决方案


那是因为你使用的useEffect函数没有依赖关系,所以每次 prop/state 发生变化时都会执行它(它就像一个类组件的componentDidUpdate)。

我建议您在Added组件中使用它,例如 a componentDidMount,以便它只执行一次。为此,您必须传递一个空的依赖数组,如下所示:

useEffect(() => {
    //fetching the data
}, []);

推荐阅读