【发布时间】:2019-06-01 22:44:28
【问题描述】:
我有一个 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”记录在主子组件中
“mounted”记录在 componentDidMount 中
【问题讨论】:
标签: javascript reactjs redux react-redux