如何从另一个文件夹导入 useState 对象

How to import an useState object from another folder

我有一个在“Creat React App”中创建的项目,我有一个 useState 数组,如下所示:

const [State, setState] = useState([]);

此数组位于名为 StateComp 的组件内的另一个文件夹中,但我还想将此数组加载到主文件夹中(在本例中为 App.js)。

我试图将 StatesetStateStateComp 文件导入到 App.js 文件,但如我所料,导入本身失败了。

有人知道吗?

您可以为此使用自定义挂钩!您可以在此处查看示例: and an example of it being called in another file here:

在此期间,这里有一个快速解决方案可以提供帮助:

import { useState, useEffect } from 'react';

export function useSomeState(someParam) {
  const [someState, setSomeState] = useState([]);

  useEffect(() => {
    // do some state logic here if you want
  });

  return { someState, setSomeState };
}

// in another file...

import { useSomeState } from './useSomeStateFile.js'

function SomeComponent = () => {
   const { someState, setSomeState } = useSomeState(someParam)
}

您可以使用 React Context to manage this or Redux。这是 React 上下文的示例:

src/providers/StateProvider.js

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

import { createContext } from "react";

const StateContext = createContext({
  state: [],
  setState: () => {},
});

export const useStateContext = () => useContext(StateContext);

const StateProvider = ({ children }) => {
  const [state, setState] = useState([]);

  return (
    <StateContext.Provider value={{ state, setState }}>
      {children}
    </StateContext.Provider>
  );
};

export default StateProvider;

src/App.js

import React from "react";
import { useStateProvider } from "./providers/StateProvider";

export default App = () => {
  const { state, setState } = useStateProvider();

  return <h1>MyApp</h1>;
};

src/index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import StateProvider from "./providers/StateProvider";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <StateProvider>
      <App />
    </StateProvider>
  </React.StrictMode>
);

reportWebVitals();