我有一个React组件,它使用react-redux connect
函数(装饰器)来设置属性。在JSX中引用此组件时,flowtype会抱怨“在React元素的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 element `Sidebar` 56: props: SidebarCmpProps ^^^^^^^^^^^^^^^ property `actions`. Property not found in... 65: ^^^^^^^^^^^ props of React element `Sidebar`
To get around the error I had to change the properties to union types of any
and add a defaultProps
, which is less than ideal
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
错误,因为您只是在activeSidebarComponent
中设置了@connect
属性,并且将动作声明为必需的属性actions: React.PropTypes.object.isRequired
。
因此,您将必须为actions
prop设置默认值或删除该限制。