reactjs React.js:可以在函数组件外部分配useState()吗?

k2arahey  于 2023-01-30  发布在  React
关注(0)|答案(3)|浏览(150)

是否有任何语法允许在函数组件之外赋值useState?到目前为止,我已经尝试过了,但它不起作用:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

function App() {
  useEffect(() => setStateData("from useEffect"), []);

  return <div className="App">{stateData}</div>;
}

const [stateData, setStateData] = App.useState("default value"); // fails
// const [stateData, setStateData] = App.prototype.useState("default value"); // also fails

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

代码沙箱:

axzmvihb

axzmvihb1#

免责声明:这是一个反模式。如果你想共享状态there's better ways,但只是为了信息...
你可以在组件外部使用useStateupdate函数,方法是将它赋给一个变量,但一定要在卸载组件时清除它。

/* Reference to hold the update function */
let updateOutside

function App() {
  const [state, update] = useState()
  
  useEffect(() => {
    /* Assign update to outside variable */
    updateOutside = update

    /* Unassign when component unmounts */
    return () => updateOutside = null
  })

  return `App State: ${state}`
}

if (updateOutside) updateOutside(/* will re-render App */)
slhcrj9b

slhcrj9b2#

是否有任何语法允许在函数组件之外分配useState?
如果你看一下文档和钩子规则

仅从React函数调用挂接

**不要从常规JavaScript函数调用钩子。**相反,您可以:

来自React函数组件的调用挂钩。
调用钩子从自定义钩子(我们将在下一页了解他们).
所以......不行,不能在功能组件之外使用useState

jv2fixgn

jv2fixgn3#

如果要在组件外部使用useState,请考虑使用https://jotai.org/
它是带有一些额外奖励的useState替换

import { atom, useAtom } from 'jotai'

// Create your atoms and derivatives
const textAtom = atom('hello')
const uppercaseAtom = atom(
  (get) => get(textAtom).toUpperCase()
)

// Use them anywhere in your app
const Input = () => {
  const [text, setText] = useAtom(textAtom)
  const handleChange = (e) => setText(e.target.value)
  return (
    <input value={text} onChange={handleChange} />
  )
}

const Uppercase = () => {
  const [uppercase] = useAtom(uppercaseAtom)
  return (
    <div>Uppercase: {uppercase}</div>
  )
}

// Now you have the components
const App = () => {
  return (
    <>
      <Input />
      <Uppercase />
    </>
  )
}

相关问题