我有一個到組件的套接字連接,但它的資料用于各種其他組件。為了降低復雜性,我嘗試使用 contextAPI 在所有其他組件之間共享內容。
這是我的套接字連接代碼:
var NotificationData="";
useEffect(() => {
if(!state.id){
return
}
var token = ((localStorage.getItem("provider__token"))?
localStorage.getItem("provider__token"): sessionStorage.getItem("provider__token")) || ''
let io=new WebSocket(
process.env.REACT_APP_BACKEND_DEVELOPMENT_URL_SOCKET
'ws/provider_notifications/'
state.id
'/'
);
io.onopen = (e) => {
io.send(JSON.stringify({'token':token}))
}
io.onmessage = (e) => {
let data=JSON.parse(e.data);
NotificationData=React.createContext(data);
if(data.type && data.type === 'notification'){
setStatus(true);
setTotalNotification(data.notifications_unread)
}
};
})
但是這樣我就無法匯出我的背景關系。我檢查了一些具有以下語法的示例:
export const UserContext = React.createContext(userContextTemplate)
但是這個例子只適用于靜態資料。
我可以做些什么來使這個背景關系資料在另一個組件中可用?
uj5u.com熱心網友回復:
創建context.js檔案
import { createContext, useContext, useState } from 'react'
//create a context
const NotificationData = createContext({})
export default NotificationData
//create a provider of that context that will provide values
//which can be used by all the children conponents
export const NotificationDataProvider = ({ children }) => {
const [notificationData, setNotificationData] = useState(null)
return (
<NotificationData.Provider value={{ notificationData, setNotificationData }}>
{children}
</NotificationData.Provider>
)
}
//create a helper custom hook to used by other components who
//wish to use the context values
export const useNotificationDataContext = () => {
const { notificationData, setNotificationData } = useContext(NotificationData)
return {
notificationData,
setNotificationData
}
}
設定資料的 Socket 檔案
...
//get the context value which will set the notification data
const { setNotificationData } = useNotificationDataContext()
useEffect(() => {
if (!state.id) {
return;
}
var token =
(localStorage.getItem("provider__token")
? localStorage.getItem("provider__token")
: sessionStorage.getItem("provider__token")) || "";
let io = new WebSocket(
process.env.REACT_APP_BACKEND_DEVELOPMENT_URL_SOCKET
"ws/provider_notifications/"
state.id
"/"
);
io.onopen = (e) => {
io.send(JSON.stringify({ token: token }));
};
io.onmessage = (e) => {
let data = JSON.parse(e.data);
//After getting the data set it using the setNotificationData.
//This will set the state in the provider and will re-render all
//the child components using the notification data, this way all
//the components using the notification data will get the updated data
setNotificationData(data);
if (data.type && data.type === "notification") {
setStatus(true);
setTotalNotification(data.notifications_unread);
}
};
});
...
你的index.js檔案
...
// Wrap your app with Notification Provider
<NotificationDataProvider>
<App />
</NotificationDataProvider>
...
在您想要使用通知資料的 cdild 組件中的某個位置
const SomeOtherComponentWhereDataIsUsed = () => {
//use the notification data in this component but beware untill it
//is set in that useEffect of the above component it will be an undefined value
const { notificationData } = useNotificationDataContext()
//use this notificationData
...
}
參考:
https://dmitripavlutin.com/react-context-and-usecontext/
https://reactjs.org/docs/context.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/482902.html
標籤:javascript 反应 插座
