gpt4 book ai didi

reactjs - React.js : Possible to assign useState() outside function component?

转载 作者:行者123 更新时间:2023-12-04 14:32:55 25 4
gpt4 key购买 nike

是否有任何语法允许分配 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);


代码沙盒: Edit objective-worker-qb20h

最佳答案

您可以使用 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 */)

关于reactjs - React.js : Possible to assign useState() outside function component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59361502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com