【问题标题】:React app with axios inside useEffect() is rendering twice在 useEffect() 中使用 axios 反应应用程序正在渲染两次
【发布时间】:2021-06-15 00:54:04
【问题描述】:

我一直试图弄清楚为什么我的绘制 BPMN 图的函数会渲染该图两次。我已经查看了在 useEffect 中使用 axios 的各种示例,但无法弄清楚为什么会发生这种情况。该 url 正在为查看器返回一个有效的 xml。

谁能给我一些指导?

这是整个函数

function RenderBPMN(pathDefinition) {
  const [diagram, setDiagram] = useState(""); 
  const container = document.getElementById("container");
  const msg = JSON.stringify(pathDefinition);
  const url = `http://localhost:9090/xml?path=${msg}`;
  
  useEffect(() => {
        const fetchData = async () => {
          axios
          .get(url)
          .then((resp) => {
            setDiagram(resp.data);
          })
          .catch ((error) => {
            console.log(error);
          });
      };
      fetchData();
  }, [url]);

  if (diagram.length > 0) {
    const viewer = new Viewer({
      container,
      keyboard: {
        bindTo: document
      }
    });
    viewer
      .importXML(diagram)
      .then(({ warnings }) => {
        if (warnings.length) {
          console.log("Warnings", warnings);
        }
        viewer.get('canvas').zoom('fit-viewport');
      })
      .catch((err) => {
        console.log("error", err.message);
      }); 
  }

  return (
      <div
        id="container"
        style={{
          border: "1px solid #010101",
          height: "50vh",
          width: "70vw",
          margin: "auto"
        }}
      ></div>
  );
}
      
export default RenderBPMN;

【问题讨论】:

    标签: axios react-hooks use-effect


    【解决方案1】:

    从 useEffect 数组中移除 url。对于空数组,它只会在组件被挂载时调用一次。

    useEffect( () => {
        // your code
    }, [ /* empty */ ])
    

    【讨论】:

    • 谢谢,但它仍然呈现两次,我收到警告:“React Hook useEffect 缺少依赖项:'url'。要么包含它,要么删除依赖项数组”
    • 我不确定,但我想我读过一次关于在开发环境中与React.StrictMode 相关的类似行为.. 尝试构建您的项目并检查是否在生产环境中工作得更好..
    猜你喜欢
    • 1970-01-01
    • 2018-08-31
    • 2022-08-19
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多