【问题标题】:React main component is called twice while using redux使用 redux 时 React 主组件被调用两次
【发布时间】: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


    【解决方案1】:

    我相信您可以通过在 componentDidmount 中提供一些额外的逻辑来解决此问题。您还应该使用您的组件state

    这样写:

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

    这实质上是说,如果您的组件已经安装过一次,那么您将不会发出您的动作创建者请求。

    【讨论】:

    • 使用状态没有改变任何东西
    【解决方案2】:

    如果您仔细观察您的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

    【讨论】:

      【解决方案3】:

      当我从项目中删除 webpack 后,问题就解决了。但是任何人都可以回答我如何在仍然使用 webpack 的同时解决这个问题。

      【讨论】:

      • 您找到解决方案了吗?我也有同样的问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2019-08-15
      • 2021-09-16
      • 1970-01-01
      • 2019-12-03
      • 2018-09-08
      • 1970-01-01
      相关资源
      最近更新 更多