为什么此React App初始化两次?

时间:2018-07-18 01:15:59

标签: reactjs webpack redux react-router redux-saga

我已经使用webpackreact-routerreduxredux-saga构建了一个React应用。

刷新时,应用会初始化两次。

我正在使用websocketsgo服务器通信,并且有一个saga在应用初始化时进行了初始化。 因为它加载两次-事件仅应触发一次,所以会触发两次。

这是我的index.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux';
import { BrowserRouter as Router } from "react-router-dom";
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga'
import thunk from 'redux-thunk';

import Root from './components/Root';
import reducers from './reducers';
import setupSocket from './actionCreators/websocketActions';

import handleNewMessage from './sagas';
import "./styles/main.scss";

const sagaMiddleware = createSagaMiddleware()

const store = createStore(
  reducers,
  applyMiddleware(sagaMiddleware, thunk)
);

const { dispatch } = store

const socket = setupSocket(dispatch)

sagaMiddleware.run(handleNewMessage, { socket, user })

ReactDOM.render(
  <Provider store={store}>
    <Router>
      <Root />
    </Router>
  </Provider>,
  document.getElementById('root')
);

如何防止此React应用在加载时初始化两次?

1 个答案:

答案 0 :(得分:0)

我知道了!

如果您使用的是html-webpack-pluginwebpack,请确保已设置 inject: false

const htmlWebPackPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html",
  inject: false,
})

我的plugins中有一个webpack.config.dev部分:

module.exports = {
  plugins: [
    htmlWebPackPlugin,
    extractSCSS
  ],
};

具有此设置的唯一奇怪效果是某些样式已更改。 想知道为什么会这样...

样式是通过webpack.config中的以下内容解决的:

 {
    test: /(\.css|\.scss)$/,
    use:['style-loader','css-loader', 'sass-loader']
 }