【问题标题】:react & redux - the component is rendering repeatedly due to api call placed in componentDidMountreact & redux - 由于在 componentDidMount 中放置 api 调用,组件重复渲染
【发布时间】:2018-11-27 11:31:20
【问题描述】:

我想在我的组件加载时进行 api 调用。我有以下代码:

import React, { Component } from "react";
import { connect } from "react-redux";
import { getProfileDetails } from "../store/actions/profileAction";

class ProfilePage extends Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.getProfileDetails(this.props.currentUser.user, "");

        console.log("COMPONENTDIDMOUNT");
    }

    render() {
        var { currentUser, getProfileDetails, profile } = this.props;
        return (
            <React.Fragment>
                <h1>Profile Page for {currentUser.user.username} !!</h1>

            </React.Fragment>
        )
    }

}

function mapStateToProps(state) {
    return ({
        currentUser: state.currentUser,
        profile: state.profile
    })
}

export default connect(mapStateToProps, { getProfileDetails })(ProfilePage);

getProfileDetails 函数:

export function getProfileDetails(user, detail) {
    return dispatch => {
        return apiCall("get", `/api/users/profile/${user.id}/${detail}`)
            .then(profileDetail => {
                dispatch(setCurrentProfile(profileDetail, detail));
                dispatch(removeError());
            })
            .catch(err => {
                dispatch(addError(err.message));
            })
    }
}

这里的函数“getProfileDetails”正在进行一个 api 调用,然后调度一个 redux 存储操作来设置配置文件详细信息。

问题在于,每次调用 getProfileDetails 时,redux 存储都会更新,组件会重新渲染,进而触发 componentDidMount 并进入无限循环

请建议如何构建它。

【问题讨论】:

  • 什么是父组件?重新渲染不应该触发componentDidMount?只有 componentDidUpdate?
  • 在父组件中,只定义了路由,我使用history.push() 来到这个页面。我相信它不仅是重新渲染,而且是拆卸和重新安装组件。当我调试时,它不会等待 api 响应,甚至在此之前它会调用 mapSateToProps。 PS- getProfileDetails 函数只是调度操作来更新配置文件,currentUser 正在由不同的 api 调用处理。
  • 我在问题描述中添加了getProfileDetails功能

标签: reactjs redux react-redux redux-thunk


【解决方案1】:

您应该使用mapDispatchToProps 而不是mapStateToProps。后者仅使用现有状态更新组件。

您提到的问题似乎在 react-redux 文档 - https://redux.js.org/faq/react-redux#react-rendering-too-often 中进行了讨论。这可能会帮助您调试。

请提供../store/actions/profileAction 文件中的代码。

【讨论】:

    【解决方案2】:

    如果它发生变化,您想要捕获的状态属性是什么?例如,如果您只想在 currentUser 更改时调用新的 fetch,您可以这样做:

    componentDidUpdate(prevProps) {
      if (prevProps.currentUser !== this.props.currentUser)
        this.props.getProfileDetails(this.props.currentUser.user, "");
    }
    

    您需要在componentDidMount 中以不同方式初始化数据,例如从状态中获取数据。然后仅在用户更改时重新获取详细信息。

    【讨论】:

    • 您好,我在问题描述中添加了getApiCall函数。问题是在调试时,它甚至在收到 api 响应之前就触发了 mapStateToProps 函数。我的目标是简单地进行 api 调用并获取有关此页面(组件)负载的配置文件详细信息。
    • 听起来您需要做的是在 componentDidMount 上调度一个操作,以使用 API 调用的结果更新您的状态
    猜你喜欢
    • 2019-06-18
    • 2019-02-20
    • 2018-03-24
    • 1970-01-01
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    相关资源
    最近更新 更多