【问题标题】:React component loads non-stopReact 组件加载不停
【发布时间】:2021-12-15 12:53:44
【问题描述】:

我的 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;

【问题讨论】:

    标签: reactjs components use-effect


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-26
      • 2023-03-22
      • 2015-01-18
      • 2021-05-07
      • 1970-01-01
      • 2022-01-26
      • 2018-06-05
      • 2021-05-26
      相关资源
      最近更新 更多