简体   繁体   English

使用redux时,两次调用React主组件

[英]React main component is called twice while using redux

I have a react main component that dispatches redux action on componentDidMount , the action will fetch API data. 我有一个反应时调度上Redux的动作主要成分componentDidMount ,动作将取API数据。

The problem is: when I start my application my componentDidMount and main component are executed twice. 问题是:当我启动应用程序时,我的componentDidMount和主组件执行了两次。 So, it makes 2 API calls for each time application loads. 因此,每次应用程序加载时,都会进行2次API调用。 API has a limit for the total number of calls I make, I don't want to reach my limit. API对我进行的调用总数有限制,我不想达到我的限制。

I have already tried fixing the issue by removing constructor, using componentWillMount problem is not solved. 我已经尝试通过删除构造函数来解决此问题,使用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;

///actions ///动作

    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);
            })
    }
}

//reducer //减速器

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 // rootreducer

import { combineReducers } from 'redux';
import DataReducer from './dataReducer';

export default combineReducers({
    data: DataReducer
});

////index ////指数

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"));

console image is posted for reference "rendered" is logged inside main component 控制台图像已发布以供参考“渲染”记录在主要组件中

"runned1" is logged inside main-subcomponent 在主子组件中记录了“ runned1”

"mounted" logged inside componentDidMount “已安装”记录在componentDidMount内部

" 在此处输入图片说明

I believe you can work around this by providing some additional logic in your componentDidmount . 我相信您可以通过在componentDidmount提供一些其他逻辑来解决此问题。 You should also make use of your component state . 您还应该利用组件state

Write something like this: 这样写:

constructor(props){
    super(props)
    this.state = {
        mounted: false
    }
}

componentDidMount(){
    if(!this.state.mounted){
        this.props.dispatchmyAction()
        this.setState({
            mounted: true
        })
    }
}

This essentially says, if your component has already mounted once, then you will not make your action creator request. 本质上说,如果您的组件已经安装了一次,那么您将不会发出动作创建者请求。

If you watch your console.log carefully you can notice that your HMR Hot Module Reloading -plugin, re-mounts your component and this is the main reason behind this occurrence. 如果您仔细查看console.log ,您会注意到HMR Hot Module Reloading Reloading -plugin重新安装了组件,这是发生这种情况的主要原因。

What this plugin does, is that it watches for your bundles code changes and on every time you save re-renders your component. 该插件的作用是,它会监视您的捆绑软件代码更改,并且每次保存时都会重新渲染您的组件。 There has been a lot of discussion as well that this plugin does not work all cases as expected. 也有很多讨论,认为该插件不能在所有情况下都可以正常工作。

Here is some material you might consider to go trough if you wish to use HMR. 如果您想使用HMR,可以考虑以下材料。

Writing about HMR - https://codeburst.io/react-hot-loader-considered-harmful-321fe3b6ca74 撰写有关HMR的文章-https: //codeburst.io/react-hot-loader-considered-harmful-321fe3b6ca74

User guide for HMR - https://medium.com/@rajaraodv/webpacks-hmr-react-hot-loader-the-missing-manual-232336dc0d96 HMR用户指南-https: //medium.com/@rajaraodv/webpacks-hmr-react-hot-loader-the-missing-manual-232336dc0d96

The problem is solved when I removed webpack from the project. 当我从项目中删除webpack时,问题已解决。 But can anyone answer how can I solve this while still using the webpack. 但是任何人都可以回答在仍然使用Webpack的情况下如何解决此问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM