React Redux Flowtype "property not found" in React 元素,从 redux connect 获取属性



我有一个反应组件,该组件使用React-Redux connect函数(装饰器)设置属性。当在JSX中引用此组件时,FlowType抱怨" 在... React Elect 的Props 中找不到的属性"

type SidebarCmpProps = {
  activeSidebarComponent: string,
  actions: { openCallMember: () => void }
}
@connect(
  (state) => {
    return { activeSidebarComponent: state.sidebar.activeSidebarComponent }
  },
  (dispatch) => ({ actions: bindActionCreators({ openCallMember }, dispatch) })
)
class Sidebar extends React.Component {
  props: SidebarCmpProps
  static propTypes = {
    actions: React.PropTypes.object.isRequired,
    activeSidebarComponent: React.PropTypes.string
  }
}

确切的错误是:

 65:             ^^^^^^^^^^^^ react元素`sidebar` 56:道具:Sidebarcmpprops              ^^^^^^^^^^^^^^^^^^属性`ancys`。在...中找不到财产 65:             ^^^^^^^^^^^ React元素的道具`sidebar'

要解决错误,我必须将属性更改为any的联合类型并添加defaultProps,该属性

不理想
type SidebarCmpProps = {
  activeSidebarComponent: any | string,
  actions: any | { openCallMember: () => void }
}
class Sidebar extends React.Component {
  static defaultProps: SidebarCmpProps = {
    actions: null,
    activeSidebarComponent: null
  }
}

有更好的解决方案吗?

好吧,您会遇到property 'actions'. Property not found in错误,因为您只是在@connect中设置activeSidebarComponent Prop,并且根据需要声明操作,请prop actions: React.PropTypes.object.isRequired

因此,您必须为actions Prop设置默认值或删除该限制。

如果要使两个组件道具可选,则应像这样定义它们:

type SidebarCmpProps = {
  activeSidebarComponent?: string,
  actions?: { openCallMember: () => void }
}

另外,我不确定提供React的Proptypes和Flowtype是否是个好主意。这是逻辑的重复,不是吗?

最新更新