我有一个react主要组件,它在componentDidMount
上调度redux操作,该操作将获取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内部
答案 0 :(得分:1)
我相信您可以通过在componentDidmount
中提供一些其他逻辑来解决此问题。您还应该使用组件state
。
写这样的东西:
constructor(props){
super(props)
this.state = {
mounted: false
}
}
componentDidMount(){
if(!this.state.mounted){
this.props.dispatchmyAction()
this.setState({
mounted: true
})
}
}
这实际上是说,如果您的组件已经安装一次,那么您将不会发出动作创建者请求。
答案 1 :(得分:1)
如果您仔细观察console.log
,您会注意到您的HMR Hot Module Reloading
插件会重新安装您的组件,这是发生这种情况的主要原因。
此插件的作用是,它监视捆绑软件代码的更改,并且每次保存时都会重新渲染组件。也有很多讨论,认为该插件不能在所有情况下都能正常工作。
如果您想使用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
答案 2 :(得分:0)
当我从项目中删除webpack时,问题已解决。但是任何人都可以回答我在仍然使用Webpack的情况下如何解决这个问题。