【问题标题】:Check whether a nested prop is not undefined in mapStateToProps检查嵌套道具是否在 mapStateToProps 中未定义
【发布时间】:2019-03-03 22:29:22
【问题描述】:

如果我们需要得到一个深度嵌套的 prop 并且值可能在每个级别都未定义。换句话说,我们需要检查每个级别的值是否未定义。什么是这样做的好习惯,或者完全避免这样做?

一个简单的二层例子,想象一下深度是五六...

const mapStateToProps = state => {
    return {
        formValues: state.form.section1 ? 
                      state.form.section1.input1? 
                        state.form.section1.input1.value 
                        : {} 
                      : {}
    };
};

我发现了这个帖子:Cannot read property something of null, mapStateToProps,但我怀疑如果树很高,这是否是一个好习惯。

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    我是这样处理这种情况的:

    const mapStateToProps = state => {
    return {
        formValues: state.form && state.form.section1 && state.form.section1.input1 ? 
          state.form.section1.input1.value : {}
       };
    };
    

    您可以避免嵌套三元运算,这是不好的做法。

    【讨论】:

    • 是的,这绝对比三元链好。也在寻找一种完全避免这种检查的方法......在许多开源项目中,我根本没有看到人们检查道具,不知道为什么。
    猜你喜欢
    • 2020-12-26
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 2018-07-25
    • 1970-01-01
    • 2014-01-23
    相关资源
    最近更新 更多