在 React Redux 中的 mapStateToProps 之前调度一个动作

Dipatching an action before mapStateToProps in React Redux

我正在 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);

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

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

您只需添加

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

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

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

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

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

您实际上 想要 调用选择器并且您 想要 它到 return undefined 这是简单的道理...