我已经使用webpack
,react-router
,redux
和redux-saga
构建了一个React应用。
刷新时,应用会初始化两次。
我正在使用websockets
与go
服务器通信,并且有一个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应用在加载时初始化两次?
答案 0 :(得分:0)
我知道了!
如果您使用的是html-webpack-plugin
和webpack
,请确保已设置
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']
}