问题描述
我有一个包装在Relay容器中的组件:
I have a component wrapped in a Relay container:
const Widget = (props) => {
return (
<div> { props.foo.bar } </div>
)
}
Widget.defaultProps = { foo: {bar: 0} }
export default Relay.createContainer(Widget, {
fragments: {
store: () => Relay.QL`
fragment on WidgetData {
foo {
bar
}
}
`
}
})
我正在为后端使用GraphQL即服务提供程序,并且当 WidgetData
的 foo
属性不存在时,它返回 null
,当我的组件尝试渲染 props.null.bar
I'm using a GraphQL-as-a-service provider for a backend, and when the foo
property of WidgetData
isn't present, it returns null
, which throws when my component attempts to render props.null.bar
据我所知, defaultProps
仅在prop是 undefined
时起作用,而不是在 null
时起作用.
As far as I know, defaultProps
only works when the prop is undefined
, not when it's null
.
在这种情况下,如何使用 defaultProps
防止 null
结果?
How can I protect against null
results with defaultProps
in this case?
希望避免为我引用的每个 prop
编写保护声明.
Hoping to avoid writing a guard statement for each prop
I reference, if possible.
推荐答案
您可以对Relay容器中的道具进行健全性检查.
You can do a sanity check for props from Relay container.
render() {
let {
foo,
...other
} = this.props;
let bar = foo ? foo.bar : '';
return (
<div> { bar } </div>
)
}
有关更多信息,请查看: https://github.com/bfwg/relay-gallery
For more info, checkout: https://github.com/bfwg/relay-gallery
这篇关于如何为包裹在Raley容器中的组件设置默认道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!