簡體   English   中英

從 React 組件調用模塊化自定義 javascript 模塊 function 兩次。 為什么會被調用兩次? 場景如下圖:

[英]Calling modular custom javascript module function twice from React component. Why is it being called twice? Scenario shown below:

希望你們都做得很好。 我已經開始學習 React 並且遇到了障礙,我有點需要你的專業知識。

所以情況如下:

當我向反應服務器發送請求時,當我嘗試在fetchTaskList方法中記錄數據時,我可以在控制台中看到,數據被打印兩次,而我只調用了一次該方法,並且到目前為止我沒有明確使用鈎子。

你能幫我理解為什么會這樣嗎? < 我是 JS 和 React 的菜鳥。 所以如果你能詳細解釋一下我就能理解/>

謝謝!

的項目的文件結構:項目的文件結構

應用程序.js:

import Wrapper from "./components/Wrapper";
import "./App.css";

function App() {
  return (
    <>
      <Wrapper />
    </>
  );
}

export default App;

包裝器.js:

import Canvas from "./functional/Canvas";

const Wrapper = (props) => {
  return <Canvas />;
};

export default Wrapper;

Canvas:

import { useEffect, useRef, useState, useContext } from "react";
import Card from "../ui/Card";
import Input, { NumberInput } from "../ui/Input";
import Button from "../ui/Button";
import { storeData, fetchTaskList } from "./Actions";

import style from "./canvas.module.css";
import Taskpane from "../ui/Taskpane";

import TaskContext from "../context/task-context";

let content = "init";
const Canvas = (props) => {
  // const [refresh, setRefresh] = useState(true);

  const ctx = useContext(TaskContext);
  const task = useRef();
  const priority = useRef();
  const timestamp = useRef();

  const addData = () => {
    storeData({
      task: task.current.getValue(),
      priority: priority.current.getValue(),
      date_: timestamp.current.getValue(),
    });
    task.current.setValue();
    priority.current.setValue();
    timestamp.current.setValue();
    // setRefresh(false);
  };

  let from_db = fetchTaskList(ctx.context_storage);
  console.log(from_db);
  content = <Taskpane className={style["task-container"]} task={from_db} />;

  return (
    <>
      <Card className={style["input__container"]}>
        <Input
          type="text"
          className={style["input-style__textbox"]}
          placeholder="Your activity.."
          ref={task}
        />
        <NumberInput
          placeholder="Priority"
          className={style["input-style__NumberInput"]}
          min="1"
          max="5"
          step="1"
          ref={priority}
        />
        <Input
          type="date"
          className={style["input-style__DateInput"]}
          placeholder="Pick a date"
          ref={timestamp}
        />
        <Button className={style["input-btn__add"]} onClick={addData}>
          Add
        </Button>
        {/* {content} */}
      </Card>
      {/* <Taskpane className={style['task-container']}>No task found.</Taskpane> */}
      {content}
    </>
  );
};

export default Canvas;

Actions.js:

import { useContext } from "react";

const Actions = (props) => {};
export default Actions;

const storeData = async function (data) {
  try {
    const response = await fetch(
      "https://mark-i-cf86f-default-rtdb.asia-southeast1.firebasedatabase.app/test_database.json",
      {
        method: "POST",
        body: JSON.stringify(data),
        headers: {
          "Content-Type": "application/json",
        },
      }
    );
    if (!response.ok) {
      console.log("Error occured!");
      return;
    }
  } catch (e) {
    console.log("Exception occured!");
  }
};

const fetchTaskList = (context_storage) => {
  try {
    fetch(
      "https://mark-i-cf86f-default-rtdb.asia-southeast1.firebasedatabase.app/test_database.json"
    )
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        if (context_storage === null) {
          console.log(data);
        }
      });
  } catch (err) {
    console.log("ERROR Occured!");
  }
  return "No task found";
};

export { storeData, fetchTaskList };

我認為發生的事情是您在 fetchTaskList function 中記錄了一次數據:

if (context_storage === null ){
            console.log(data);
        }

當你打電話給它時。

let from_db = fetchTaskList(ctx.context_storage);

控制台.log(from_db);

您可以將您的 fetchTaskList function 重構為如下所示:

const fetchTaskList = async (context_storage) => {

try{
    let response = await fetch('https://mark-i-cf86f-default-rtdb.asia-southeast1.firebasedatabase.app/test_database.json');

    let data = await response.json();

    return data;
    
}catch(err){
    console.log("ERROR Occured!");
}
return "No task found";

}

async/await 是另一種處理 Promise 的方式。

數據顯示兩次,因為您在數據上調用了 console.log 兩次。

一次在 Action.js 的 function 內部,然后在您調用 Canvas.js 內部的 function 之后立即再次。 這就是您在控制台中看到兩次數據的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM