首页 > 解决方案 > 反应 | 未定义解构赋值时传递默认道具值时出错

问题描述

我的理解是有几种方法可以将默认值传递给 React 中的 prop。

但是,我尝试过的所有方法似乎都没有缓解我的问题。

本质上,我希望有一个默认值来防止未定义的值完全破坏应用程序。

useContext()即带有钩子的React App

const context = useContext(FarmContext)

// destructuring assigment 
const { fruit = 'foobar' } = context.data.farm[0] // apple


*****
<Compoment fruit={fruit} /> // apple

我的问题:

如果在将上述数据链接到以下任一位置时出现错误/错字: cooontextdatttafarm[55]

该应用程序与cannot read property ________ of undefined

因此,我的 destructed fruit = 'foobar' never kick 到位。

// does not work if there's a typo on object chaining
const { fruit = 'foobar' } = context.DA23ta.farm[0] // farm is undefined

*******
<Compoment fruit={fruit} /> // app breaks

此外,我尝试传递默认的道具值方法:

// does not work if there's a typo
const { fruit } = context.DA23ta.farm[0] // farm is undefined

*******
<Compoment fruit={fruit || 'foobar'} /> // app breaks

我也尝试过通过defaultProps作为替代方案,但我也无法缓解这个问题。

我得到这个有点工作的唯一场景是当我将数据构造为:

const fruit = context.data.farm[0].fruuuit // big typo at the end here


// prop will render as 'foobar' bellow
<Compoment fruit={fruit || 'foobar'} /> // foobar

无论数据发生什么(错别字,超时未定义的值),我都希望我的代码具有后备值。

我希望该后备默认值位于解构分配中。

如果在任何地方(不仅仅是我上面显示的最后一个链接对象)出现错字/中断,我如何添加预防性防御策略:

const { fruit = 'foobar' } = contExt.dAta.farMM[0]

我怎么能在另一边获胜并作为水果道具返回 foobar,而不是因为一个未定义的道具而让我的整个应用程序中断?

这是可能的还是可行的?我对我没有在这里展示的其他策略(如果有的话)持开放态度。

标签: javascriptreactjsecmascript-6react-hooksreact-context

解决方案


好像你需要像 Ramda's pathOr这样的东西。它将通过给定路径返回值,如果值存在,则返回提供的默认值。

const data = {
  context: {
    data: {
      farm: [
        { fruit: 'apple' },
        { fruit: 'orange' }
      ]
    }
  }
}

const getFruit = R.pathOr('foobar', [ 'context', 'data' , 'farm' , 0, 'fruit' ])
const getFruitWithTypos = R.pathOr('foobar', [ 'contExt', 'dataaaa' , 'form' , 0, 'fruuuuuit' ])

console.log(getFruit(data))
console.log(getFruitWithTypos(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


推荐阅读