1

所以我有这个问题,它没有合并两个对象,因为在渲染后调用 useEffect 时refsContext为空。它仅以对象中的一个引用结束。useEffect(() => {setRef(something)}, [ref]);导致无限的空对象循环。我错过了什么?

refs.context.jsx

import { createContext } from "react";
const refsContext = createContext({});
export default refsContext;

多个文件的相同代码

/** @jsx jsx */
import React, { useContext, useEffect, useRef } from "react";
import refsContext from "../../context/refs.context";

const StackoverflowExample= () => {
  const projectsRef = useRef(null);
  const [ref, setRef] = useContext(refsContext);

  useEffect(() => {
    setRef({ ...ref, projects: projectsRef.current });
  }, []);

  return (
     <section ref={projectsRef}></section>
  );
};

export default StackoverflowExample;

应用程序.jsx

import React, { useState, useEffect } from "react";
import { render } from "react-dom";
import Pages from "./Pages";
import { BrowserRouter } from "react-router-dom";
import refsContext from "./context/refs.context";


const App = () => {
  //Default Contexts
  const refsHook = useState({});

  console.log(refsHook[0]);

  //All my wrappers/providers for my App
  return (
    <refsContext.Provider value={refsHook}>
       <BrowserRouter>
          <Pages/>
       </BrowserRouter>
    </refsContext.Provider>
  );
};

render(<App />, document.getElementById("root"));


4

0 回答 0