[英]Import States and Functions to a React Component
是否可以在功能性 React 組件上導入狀態和函數以使其更清潔?
這是我的代碼目前的樣子:
import React from 'react'
//more imports...
const Dashboard = () => {
const [] = useState()
//more states here..
const fetch = asycn () => {
//more code..
}
//more functions here...
return (
<>
</>
)
}
但是,我想知道是否可以分離所有狀態和功能,以便我的反應組件文件看起來像這樣:
import React from 'react'
//more imports...
//import states and functions
const Dashboard = () => {
return (
<>
</>
)
}
有沒有其他方法可以導入它以供我使用該組件內的數據? (除了自定義鈎子來最小化我的代碼)
您可能想查看 Redux,它用於在全局商店中集中 state,可以在整個應用程序中訪問。
但是,您需要使用鈎子,useSelector() 來訪問 state,並且 useDispatch() 來調度新的 state。
您還可以通過父組件中的道具傳遞 state,
const Dashboard = ({state, setState}) => {
return (
<>
</>
)
}
但是,那么父組件會有很多const [state, setState] = useState()
對於復雜的狀態和您所描述的內容,您需要使用 redux。 https://redux.js.org/introduction/examples
對於本地和簡單的 state useState 是最佳選擇
希望我的回答能指導你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.