【问题标题】:React | Error Passing Default Props Values When Destructuring Assignment is Undefined反应 |未定义解构赋值时传递默认道具值时出错
【发布时间】:2019-04-28 18:47:37
【问题描述】:

我的理解是有几种方法可以将默认值传递给 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 而中断

因此我的 destructured 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]

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

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

【问题讨论】:

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


    【解决方案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))
    &lt;script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"&gt;&lt;/script&gt;

    【讨论】:

    • 这很有趣。谢谢你张贴。虽然很遗憾,这不能用 JavaScript 原生完成(?)
    • @NullisTrue 好吧,有一种称为可选 chaning 提案的“本机”方法,您现在可以使用它,例如 babel 插件 github.com/tc39/proposal-optional-chaining。但它仅处于第一阶段,可能不会包含在 ES 标准中。此外,它还需要从简单的 .?. 的语法进行小的更改
    【解决方案2】:

    可选的链接来救援!

    可选链接是fairly well supported now

    const context = useContext(FarmContext)
    
    // destructuring assigment 
    const { fruit = 'foobar' } = context?.data?.farm?.[0] ?? {} // apple
    
    
    <Component fruit={fruit} /> // apple
    
    

    另外,如果可以的话,你可以使用defaultProps

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 2020-12-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 2020-01-11
      相关资源
      最近更新 更多