如何在Reactjs中导入setState函数

huangapple go评论87阅读模式
英文:

How to import the setState function in reactjs

问题

在组件目录中的 Editor.js 文件中包含以下内容:

const Editor = () => {
  //一些状态
  const [mathEditorVisible, setMathEditorVisible] = useState(false);
  //一些其他代码
}

这是位于 utils 目录中的 Form.js 文件:

//一些导入
export const handleSaveFormula = (latex) => {
  //一些代码
  setMathEditorVisible(false);   
};

这是位于 utils 目录中的 Editor.js 文件:

//一些导出
export const editExpression = () => {
  //一些代码
  setMathEditorVisible(true);
};

现在,我想要从组件目录中的 Editor.js 文件导入 setMathEditorVisible,并将其定义引入到 utils 目录中的 Editor.js 和 Form.js 文件中。如果不导入它,将会发生以下错误:

src/utils/Editor.js
  Line 17:8:  'setMathEditorVisible' is not defined  no-undef

src/utils/Form.js
  Line 49:7:  'setMathEditorVisible' is not defined  no-undef

当然,这会发生因为它目前未定义。

英文:

The file Editor.js in the components directory contains this

const Editor = () => {
  //some states
  const [mathEditorVisible, setMathEditorVisible] = useState(false);
  //some other code
}

This is Form.js in the utils directory:

//some imports
export const handleSaveFormula = (latex) => {
  //some code
  setMathEditorVisible(false);   
};

This is Editor.js in the utils directory:

//some exports
export const editExpression = () => {
  //some code
  setMathEditorVisible(true);
};

Now, I want to import the setMathEditorVisible from Editor.js in the components directory where it is defined to the Editor.js and Form.js files in the utils directory.
This error occurs if I do not import it

src/utils/Editor.js
  Line 17:8:  'setMathEditorVisible' is not defined  no-undef

src/utils/Form.js
  Line 49:7:  'setMathEditorVisible' is not defined  no-undef

And of course it will because it is undefined for now.

答案1

得分: 0

以下是您要翻译的内容:

错误的原因是因为您无法在函数中导入本地变量。

不过,请不要担心,这个问题可以用其他几种方式解决:

参数

您可以将 mathEditorVisiblesetMathEditorVisible 传递给 Editor,并将其传递给您的 handleSaveFormulaeditExpression 函数,这些函数来自于更高级别的组件(例如页面)。

它会看起来像这样:

// page.tsx
const Page = () => {
  ...
  const [mathEditorVisible, setMathEditorVisible] = useState(false)
  ...
  return <>
   ...
   <Editor visible={mathEditorVisible} /> 
   ...
   <button onClick={() => {
     setMathEditorVisible(false)
     handleSaveFormula()
   }}>Your submit flow</button>
   <button onClick={() => {
     setMathEditorVisible(true)
     editExpression()
   }}>Your edit flow</button>
  </>
}

上下文

另一种方法是将您的变量放入上下文中(这必须位于 Editor 组件的顶部以及您正在调用 setMathEditorVisible 的函数中)。

上下文允许您在任何(甚至是嵌套的)子组件中访问其值。

因此,在这种情况下,您可以将 [mathEditorVisible, setMathEditorVisible] 存储在上下文组件(ContextObject.Provider)的 value 属性中,该上下文组件由 React.createContext 创建。然后,稍后您可以通过 useContext 钩子访问这些值,将原始上下文对象作为参数传递。

这是一个示例:

// mathEditor.tsx
const EditorContext = React.createContext<[boolean, (v: boolean) => void]>([false, () => {}])

const Editor = () => {
  const [mathEditorVisible] = useContext(EditorContext)
  ...
}

// page.tsx

import { EditorContext } from './mathEditor.tsx' // 或任何其他路径

const SubmitFlow = () => {
  ...
  const [,setMathEditorVisible] = useContext(EditorContext)
  return <>
    ...
    <button onClick={() => setMathEditorVisible(false)}>Submit</button>
  </>
}
const EditFlow = () => {
  ...
  const [,setMathEditorVisible] = useContext(EditorContext)
  return <>
    ...
    <button onClick={() => setMathEditorVisible(true)}>Edit</button>
  </>
}

const Page = () => {
  const [mathEditorVisible, setMathEditorVisible] = useState(false)
  return <>
    ...
    <EditorContext.Provider value={[mathEditorVisible, setMathEditorVisible]}>
      <Editor />
      <SubmitFlow />
      <EditFlow />
    </EditorContext.Provider>
  </>
}

请注意,使用上下文时,由于您必须调用 useContext 钩子,您需要在组件中检索值,并根据需要将其传递给底层函数。

结论

正如其他人已经提到的,您可能最好使用第一种方法。不过,了解上下文的工作原理也很重要,以防您需要在许多不相关的组件/位置中访问某些内容。

英文:

The reason you're getting the error is because you can't import a local variable in a function.

However, fear not, this problem can be solved in a couple other ways:

Parameters

You can pass mathEditorVisible and setMathEditorVisible into Editor and into your handleSaveFormula and editExpression functions from component of a higher level (e.g. page).

It will look something like this:

// page.tsx
const Page = () =&gt; {
  ...
  const [mathEditorVisible, setMathEditorVisible] = useState(false)
  ...
  return &lt;&gt;
   ...
   &lt;Editor visible={mathEditorVisible} /&gt; 
   ...
   &lt;button onClick={() =&gt; {
     setMathEditorVisible(false)
     handleSaveFormula()
   }}&gt;Your submit flow&lt;/button&gt;
   &lt;button onClick={() =&gt; {
     setMathEditorVisible(true)
     editExpression()
   }}&gt;Your edit flow&lt;/button&gt;
  &lt;/&gt;
}

Context

Another way to do this is put your variables into context (which would have to be on top of Editor component and the functions you're calling setMathEditorVisible in).

Context lets you access its values in any (even nested) child components.

So, in this situation you would store your [mathEditorVisible, setMathEditorVisible] in value property of a context component (ContextObject.Provider) created by React.createContext. Then later you can access the values through useContext hook, passing the original context object as the argument.

Here's the example:

// mathEditor.tsx
const EditorContext = React.createContext&lt;[boolean, (v: boolean) =&gt; void]&gt;([false, () =&gt; {}])

const Editor = () =&gt; {
  const [mathEditorVisible] = useContext(EditorContext)
  ...
}


// page.tsx

import { EditorContext } from &#39;./mathEditor.tsx&#39; // Or any other path


const SubmitFlow = () =&gt; {
  ...
  const [,setMathEditorVisible] = useContext(EditorContext)
  return &lt;&gt;
    ...
    &lt;button onClick={() =&gt; setMathEditorVisible(false)}&gt;Submit&lt;/button&gt;
  &lt;/&gt;
}
const EditFlow = () =&gt; {
  ...
  const [,setMathEditorVisible] = useContext(EditorContext)
  return &lt;&gt;
    ...
    &lt;button onClick={() =&gt; setMathEditorVisible(true)}&gt;Edit&lt;/button&gt;
  &lt;/&gt;
}

const Page = () =&gt; {
  const [mathEditorVisible, setMathEditorVisible] = useState(false)
  return &lt;&gt;
    ...
    &lt;EditorContext.Provider value={[mathEditorVisible, setMathEditorVisible]}&gt;
      &lt;Editor /&gt;
      &lt;SubmitFlow /&gt;
      &lt;EditFlow /&gt;
    &lt;/EditorContext.Provider&gt;
  &lt;/&gt;
}

Note that with context, since you have to call useContext hook, you would need to retrieve values in a component, and if needed, pass it to underlying functions.

Conclusion

As some other people already mentioned, you're probably better off with the first approach. However, it's good to know how context works, in case you need to access something in a lot unconnected components/places.

答案2

得分: 0

我只是将状态作为参数传递给需要管理它的函数,它按预期工作了,谢谢各位!

英文:

I just passed the state as an argument to the functions where I need to manage it and it works as expected, thank you guys for your consideration!

huangapple
  • 本文由 发表于 2023年7月3日 06:22:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76601006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定