如何在挂钩中传递对象参数?

时间:2019-11-26 03:52:16

标签: javascript reactjs react-hooks

如下所示,我将参数 list 传递给useFunction;在useGetName函数中,出于某种原因,我需要将控制参数“ data”作为“ item”。事实证明是循环更新。

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

function App() {
  const [filter, setFilter] = useState([]);

  useEffect(() => {
    const id = setTimeout(() => {
      setFilter([{ value: "" }]);
    }, 1000);
    return () => {
      clearTimeout(id);
    };
  }, []);

  const list = [
    {
      name: "a",
      value: filter
    }
  ];

  return <div>{useGetName(list)}</div>;
}

function useGetName(data) {
  const [item, setItem] = useState(data);

   useEffect(() => {
    // for some reason, I need control params "data" as "item"
    console.log("data", data);
    setItem(data);
  }, [data]);

  return (
    <div
      onClick={() => {
        console.log("item", item);
      }}
    >
      click me
    </div>
  );
}

export default App;

我固定过的方式:


  useEffect(() => {
    console.log("data", data);
    setItem(data);
  }, [JSON.stringify(data)]);  // JSON.stringify


如何解决?谢谢

0 个答案:

没有答案