【问题标题】:react hot reloading issues using ref使用 ref 反应热重载问题
【发布时间】: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"
  }

【问题讨论】:

    标签: reactjs react-hot-loader


    【解决方案1】:

    我还没有找到解决这个问题的方法。我发现自己处于需要替换为使用另一个不使用 refs 的库的情况。

    我尝试了不同的钩子来处理初始化,我尝试删除所有钩子并移动到反应组件而不是功能组件,结果是一样的。

    在简单的场景中,这个库可能很好,但我最终使用了 react toastify,因为我需要在 axios 拦截器、react intl、react 和 toast 库之间创建一个桥。

    【讨论】:

    • 你找到解决办法了吗?
    猜你喜欢
    • 2018-04-30
    • 2017-06-24
    • 2016-09-27
    • 2013-06-12
    • 2019-09-14
    • 2022-07-18
    • 2019-07-08
    相关资源
    最近更新 更多