【发布时间】:2019-09-21 03:41:40
【问题描述】:
我有以下两个 react 组件,一个是主 App,另一个是使用 react-notification-component 的通知组件。我省略了一些我认为不那么重要的代码部分。
请注意日志。
import ReactNotification from "react-notifications-component"
function App() {
const notificationDOMRef = useRef(null)
return (
<>
<ReactNotification ref={notificationDOMRef} />
{
notificationDOMRef &&
<Notification notificationDOMRef={notificationDOMRef}>
...
</Notification>
}
</>
)
}
export const NotificationContext = React.createContext();
function Notification({ notificationDOMRef, intl, children }) {
const [actions, setActions] = useState(null)
console.log("Notification");
useEffect(() => {
console.log("Effect");
const pushNotification = (errorType) => notificationDOMRef.current.addNotification(errorType)
}, [])
return (
<NotificationContext.Provider value={{actions}}>
{children}
</NotificationContext.Provider>
)
}
以下情况仅在开发环境运行时发生。启用热重载。
当我启动开发环境并运行成功的查询时,会出现一个绿色框通知我。在这个过程中只打印了一个Effect关键字。
现在,如果我更改代码中的某些内容,例如将字符串 Effect 更改为 Eff 并保存,应用程序将重新加载,但是当我单击保存按钮时,我收到一条错误消息:Uncaught (in promise) TypeError: Cannot read property 'addNotification' of null in the @ 987654326@。如果我尝试在 Chrome 中调试,addNotification 函数存在于 context 上,但应用程序将其视为 null。
有什么想法吗?是我做错了什么还是这是热重载的问题?
PS:useEffect 是必要的,因为我只设置一次(初始化时)一些axios 拦截器。
PS2:如果我禁用热重新加载,页面会完全刷新并且一切正常。所以问题只在开发模式下。
"devDependencies": {
...
"react-hot-loader": "4.6.5",
"webpack": "4.29.1",
"webpack-cli": "3.2.1",
"webpack-dev-server": "3.1.14",
"webpack-merge": "4.2.1"
},
"dependencies": {
"axios": "0.18.0",
"react": "16.8.6",
"react-dom": "16.8.6",
"react-intl": "2.8.0",
"react-notifications-component": "1.1.1",
"react-router-dom": "4.3.1"
}
【问题讨论】: