【发布时间】: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
我的问题:
如果在将上述数据链接到以下任一位置时出现错误/错字:
cooontext 或 dattta 或 farm[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