Reactjs 如何为包装在Raley容器中的组件设置默认道具?

Reactjs 如何为包装在Raley容器中的组件设置默认道具?,reactjs,graphql,relayjs,relay,Reactjs,Graphql,Relayjs,Relay,我将一个组件包装在继电器容器中: const Widget = (props) => { return ( <div> { props.foo.bar } </div> ) } Widget.defaultProps = { foo: {bar: 0} } export default Relay.createContainer(Widget, { fragments: { store: () => Relay.QL`

我将一个组件包装在继电器容器中:

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
          }
        }
        `
   }
})
const小部件=(道具)=>{
返回(
{props.foo.bar}
)
}
Widget.defaultProps={foo:{bar:0}
导出默认中继.createContainer(小部件{
片段:{
存储:()=>Relay.QL`
WidgetData上的片段{
福{
酒吧
}
}
`
}
})
我正在为后端使用GraphQL-as-a-service提供程序,当
WidgetData
foo
属性不存在时,它返回
null
,当我的组件尝试呈现
props.null.bar

据我所知,
defaultProps
仅在prop
未定义时有效,而不是在
为null时有效

在这种情况下,如何使用
defaultProps
防止
null
结果


如果可能的话,希望避免为每个
道具
I引用编写保护语句。

您可以从中继容器中对道具进行健全性检查

render() {
  let {
    foo,
    ...other
  } = this.props;   
  let bar = foo ? foo.bar : '';
  return (
    <div> { bar } </div>
  )
}
render(){
让{
福,
……其他
}=这是道具;
设bar=foo?foo.bar:“”;
返回(
{bar}
)
}

有关更多信息,请签出:

您可以对中继容器中的道具进行健全性检查

render() {
  let {
    foo,
    ...other
  } = this.props;   
  let bar = foo ? foo.bar : '';
  return (
    <div> { bar } </div>
  )
}
render(){
让{
福,
……其他
}=这是道具;
设bar=foo?foo.bar:“”;
返回(
{bar}
)
}

要了解更多信息,checkout:

可以手动重写构造函数:
const bar=props.foo | |“default”
{bar}
是的,这就是我现在正在做的,但是如果使用大量/深度嵌套的道具,它可能会变得非常乏味
defaultProps
感觉更合适,尤其是因为我已经为
propTypes
定义了我的
prop
形状,我通过将中继查询向上移动到包含的组件并传递结果来解决这个问题。这样,我就不会在想要使用
defaultProps
的级别上使用中继。这可能不适用于您的情况。您可以手动重写构造函数:
const bar=props.foo | |“default”
{bar}
是的,这就是我现在正在做的,但是如果使用大量/深度嵌套的道具,它可能会变得非常乏味
defaultProps
感觉更合适,尤其是因为我已经为
propTypes
定义了我的
prop
形状,我通过将中继查询向上移动到包含的组件并传递结果来解决这个问题。这样,我就不会在想要使用
defaultProps
的级别上使用中继。这可能不适用于您的情况。