javascript - 反应 | 未定义解构赋值时传递默认道具值时出错
问题描述
我的理解是有几种方法可以将默认值传递给 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
因此,我的 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
,而不是因为一个未定义的道具而让我的整个应用程序中断?
这是可能的还是可行的?我对我没有在这里展示的其他策略(如果有的话)持开放态度。
解决方案
好像你需要像 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>
推荐阅读
- excel - 过滤后删除蓝色行
- javascript - 3rd 方库与用于编码 Html 实体以防止 XSS 的简单函数,想法?
- python - 从python字符串中提取数字
- typescript - 始终返回参数数组的值函数的打字稿定义
- electron - ElectronJS Frontend 发布后可以修改吗?
- javascript - 关于 Cache-Control HTTP 标头的混淆
- java - docker image 构建另一个镜像
- git - 如何完成 git submodule update --init --recursive 离线?
- javascript - 为什么 router.query 在第一次渲染时在 NextJS 中返回一个空对象?
- python - 函数参数内的函数调用