【问题标题】:Adding React-Redux to a React app with React.StrictMode tag使用 React.StrictMode 标签将 React-Redux 添加到 React 应用程序
【发布时间】:2020-07-11 14:31:10
【问题描述】:

最新的 create-react-app 默认在组件周围有<React.StrictMode> 标签。我看到的每个将 react-redux 添加到应用程序的示例都没有 React.StrictMode 标签。

这是我所做的:

<Provider store={store}>
  <React.StrictMode>
    <App />
  </React.StrictMode>
</Provider>,
document.getElementById('root')

但是,我总是看到:

<Provider store={store}>
  <App />
</Provider>,
document.getElementById('root')

我阅读了StrictMode 的用途。我认为它有助于调试和洞察应用程序中的问题,所以我想在开发时保留它。我所做的是否正确,还是应该像所有示例中的 Provider 一样完全替换它?

【问题讨论】:

    标签: javascript reactjs react-redux


    【解决方案1】:

    React.StrictMode 也应该包装整个应用程序,包括提供程序。所以改变你的代码如下:

    来自

      <Provider store={store}>
        <React.StrictMode>
          <App />
        </React.StrictMode>
      </Provider>,
      document.getElementById('root')
    

    收件人

      <React.StrictMode>
        <Provider store={store}>
          <App />
        </Provider>
      </React.StrictMode>,
      document.getElementById('root')
    

    【讨论】:

    • 明白了,为什么有这么多 index.js 示例从不显示 React.StrictMode?它是在更高版本的 React 中添加的还是不受欢迎的?即使我有时会收到重复的控制台日志,对我来说似乎也很有用。
    • React.StrictMode 是在 16.3 版本中引入的。同样在生产情绪中,这应该被删除。在开发过程中,许多开发人员不喜欢它,因为它会渲染组件两次。希望该解决方案对您有效。
    • 非常感谢您的解释。如果您不介意回答,另一个小问题有些无关紧要。我一直在构建没有 redux 的 react 应用程序,所以我有一堆 service.js 文件,它们使用 axios 来进行我所有的 API 调用。现在有了 redux,我已经创建了动作。保留我的服务并在操作中调用它们或者只是用操作文件完全替换我的服务是否合适。我假设这是偏好,但任何见解都会很棒。
    • 如果你在使用 Redux 并且需要调用 API,那么你可以使用 middlewareRedux-thunk 这样更方便和高效,并且可以让你控制异步 API打电话。
    猜你喜欢
    • 2018-07-21
    • 2017-10-24
    • 1970-01-01
    • 2016-08-06
    • 2016-01-27
    • 2016-03-23
    • 2019-08-22
    • 2020-09-20
    • 2020-05-10
    相关资源
    最近更新 更多