javascript - 使用 redux 时 React 主组件被调用两次
问题描述
我有一个在 上调度 redux 操作的反应主组件componentDidMount
,该操作将获取 API 数据。
问题是:当我启动我的应用程序时,我的componentDidMount
主要组件被执行了两次。因此,每次应用程序加载时,它都会进行 2 次 API 调用。API 对我进行的调用总数有限制,我不想达到我的限制。
我已经尝试通过删除构造函数来解决问题,使用componentWillMount
问题没有解决。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../redux/actions/fetchActions';
import TableHeader from './tableHeader';
class Main extends Component {
componentDidMount() {
console.log("mounted");
// this.props.dispatch(actions.fetchall("market_cap"));
}
render() {
console.log("rendered");
// console.log(this.props.cdata);
// console.log(this.props.cdata.data.data_available);
return <div className="">
<TableHeader {...this.props} />
</div>
}
}
export default Main;
///动作
import axios from 'axios';
export function fetchall(sort) {
return function (dispatch) {
axios.get(`https://cors-anywhere.herokuapp.com/https:-----------`)
.then(function (response) {
dispatch({
type: 'FETCH_DATA',
payload: response.data
})
})
.catch(function (error) {
console.log(error);
})
}
}
//减速器
let initialState = {
coins: [],
data_available: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case 'FETCH_DATA':
return {
...state,
coins: action.payload,
data_available: true
}
default: return state;
}
}
//rootreducer
import { combineReducers } from 'redux';
import DataReducer from './dataReducer';
export default combineReducers({
data: DataReducer
});
////指数
import {createStore, applyMiddleware} from 'redux';
import MapStateToProps from './components/mapStateToProps';
import rootReducer from './redux/reducers/rootReducer';
import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
//const initialState = {};
const middleware = [thunk];
const store = createStore(rootReducer, applyMiddleware(...middleware));
ReactDOM.render(<Provider store={store}><MapStateToProps/></Provider>, document.getElementById("root"));
发布控制台图像以供参考 “渲染”记录在主要组件中
“runned1”记录在主子组件中
“已安装”记录在 componentDidMount 中
解决方案
如果您console.log
仔细观察,您会注意到您的 HMR Hot Module Reloading
-plugin 重新安装了您的组件,这是发生这种情况的主要原因。
这个插件的作用是,它会监视你的包代码更改,并在你每次保存时重新渲染你的组件。也有很多讨论认为这个插件不能像预期的那样在所有情况下都有效。
如果你想使用 HMR,这里有一些你可能会考虑的材料。
写关于 HMR - https://codeburst.io/react-hot-loader-considered-harmful-321fe3b6ca74
HMR 用户指南 - https://medium.com/@rajaraodv/webpacks-hmr-react-hot-loader-the-missing-manual-232336dc0d96
推荐阅读
- html - 如何使月份输入字段的内容居中?
- php - 如何使用 pdo 执行功能来选择表?
- java - Mongodb获取Java的特定字段
- python - 如何修复 Python 中的“TypeError:'int' object is not iterable”错误
- sql - 没有为一个或多个必需参数指定值插入错误
- node.js - 如何修复 MongoError:geoNear 没有地理索引
- angular - 在 Angular 中创建侧边栏导航时出错
- c# - 读取值以外的其他部分中的设置
- angular - 测试运行时未初始化 Datepicker 和 Timepicker
- excel - 限制文件扩展名出现在电子邮件宏附件中的次数