【问题标题】:Dipatching an action before mapStateToProps in React Redux在 React Redux 中的 mapStateToProps 之前调度一个动作
【发布时间】:2017-11-01 23:38:06
【问题描述】:

我正在 react 中的一个 userProfile 容器组件,它在从服务器获取数据后显示一些数据。

这是组件:

import React from 'react';
import {connect} from 'react-redux';
import PersonalInformationView from './PersonalInformationView';
import * as selectors from '../../../reducers';

    class PersonalInformationViewContainer extends React.Component{
        constructor(props, context){
            super(props, context);

        }

        render(){
            return (
                    <PersonalInformationView userProfile={this.props.userProfile}/>
            );
        }

    }


    const mapStateToProps = (state, ownProps) => {
        return {
            user: selectors.getUser(state),
            userProfile: selectors.getUserProfile(state)
        };
    };

    const mapDispatchToProps = () =>{
        return {

        };
    };
    export default connect(mapStateToProps, mapDispatchToProps)(PersonalInformationViewContainer);

我遇到的问题是我需要调用 FETCH_USER_PROFILE_STARTED 调用 saga 并带来数据的动作。这需要在调用选择器 getUserProfile 之前完成,因为上面的代码结果是未定义的。

确保我已完成数据获取的最佳方法是什么,以便我的组件中没有未定义 props.userProfile?

【问题讨论】:

    标签: reactjs react-redux redux-saga


    【解决方案1】:

    你可以简单地添加

    if (!this.props.userProfile)
      return null;
    

    在您的渲染方法的开头,以便组件呈现为空。

    或在等待获取时呈现加载文本或动画而不是 null。

    或者通过将测试放在组件层次结构中的更高层,根本不渲染组件...

    从技术上讲,您可以避免在 fetch 开始之前调用 getUserProfile 选择器,但这最终会导致不必要的复杂、丑陋、不可维护和不可读的代码……您为什么要这样做?

    你实际上想要调用选择器并且你想要它返回undefined这是一个简单的事实......

    【讨论】:

    • 感谢您的回答。还有一个问题。我应该在哪里调用调度来获取用户配置文件?
    • 例如,您可以使用componentDidMount,但这取决于您的需要。
    猜你喜欢
    • 2020-04-23
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    相关资源
    最近更新 更多