反应|在解构分配未定义时传递默认属性值时出错

时间:2019-04-28 18:47:37

标签: javascript reactjs ecmascript-6 react-hooks react-context

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

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

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

即带有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

中断

因此,我变形的水果='foobar'从来没有踢过。

// 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

此外,我还尝试通过默认的prop值方法:

// 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作为水果道具,并且由于一个未定义的道具而没有让我的整个应用中断?

这是否可能或可行?我愿意接受此处未显示的其他策略(如果有的话)。

1 个答案:

答案 0 :(得分:1)

似乎您需要类似Ramda的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>

相关问题