【问题标题】:Cannot read property something of null, mapStateToProps无法读取 null 的属性,mapStateToProps
【发布时间】:2019-01-07 18:27:49
【问题描述】:

说我有这个:

const mapStateToProps = ({
    amount: {
        monthly: { cost },
    },
}) => ({
    amount,
    period,
    interval,
})

它抱怨它无法读取 null 的 cost

这是因为每月的东西是空的

如果每月为空,我是否可以只为 cost 返回空?

我尝试过cost: cost || null 之类的,但无济于事

有什么想法吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    可能monthly 是undefined。您可以尝试在解构过程中设置默认值:

    const mapStateToProps = ({
        amount: {
            monthly: { cost } = { cost: null },
        },
    }) => ({
      // ...
    });
    

    【讨论】:

    • 我已更改代码以作为反应道具传递。那么它看起来像这样:const { cost } = monthly,我如何在这里设置成本?
    【解决方案2】:

    在reducers中,你可以定义默认值:

    const initialState = {
      amount: {
            monthly: {},
        }
    }
    reducers = (state =initialState  )=>{
      ....
      return state;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-29
      • 2016-11-24
      • 2012-04-29
      • 2019-05-31
      相关资源
      最近更新 更多