如何为包裹在Raley容器中的组件设置默认道具? [英] How do I set default props for a component wrapped in a Raley container?

查看:48
本文介绍了如何为包裹在Raley容器中的组件设置默认道具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包装在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容器中的组件设置默认道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆