我在React中使用了Flow v.0.52类型,但在正确分配默认道具方面遇到了问题。
News.jsx
class News extends Component {
static defaultProps = {
postList: {apiData: [], total: '0'},
};
componentDidMount() {
this.props.getPostListData(this.props.lang, null, this.props.category);
}
props: {
postList: {apiData: Array<Content>, total: string},
getPostListData: Function,
};
render() {
const { postList } = this.props;
let renderNewsCards;
if (postList.apiData.length !== 0) {
renderNewsCards = (
<NewsCards ... />
);
} else {
renderNewsCards = <p style={{ textAlign: 'center' }}>Loader...</p>;
}
...在News.jsx组件中,忽略默认道具,结果postList.apiData.length遇到类型错误Uncaught TypeError: Cannot read property 'length' of undefined。
News.jsx P.S. https://gist.github.com/Y-Taras/6cb04d51d7c0561f9396e562640d3bbf 提交
发布于 2017-10-10 13:25:40
你发布的所有代码看起来都很好。
根据此错误消息:
Uncaught TypeError: Cannot read property 'length' of undefined
我们可以推断postList.apiData是未定义的,而postList确实是一个对象。在什么情况下会发生这种情况?在您提供的链接中,postList在connect()过程中被绑定到redux存储中的某个内容。
当yourReduxStore.postlistData是空对象时,您收到的错误将发生。在这种情况下,将不会使用默认的道具,因为{}是一个真实的值。
发布于 2017-09-23 18:08:42
我觉得打字有些问题,我在流脚本方面没有多少经验。但下面的方法会有效的!你能试着回答吗?
import * as React from 'react'
type Content = number // assumed content type as number
type Props = {
postList: {apiData: Array<Content>, total: string},
getPostListData: Function,
lang: string,
category: string
}
class News extends React.Component<Props> {
static defaultProps = {
postList: {apiData: [], total: '0'},
lang: 'defaultLanguage',
category: 'defaultCategory'
}
componentDidMount() {
return this.props.getPostListData(this.props.lang, null, this.props.category)
}
render() {
const { postList } = this.props;
return postList.apiData.length !== 0 ?
<div> news Cards </div> :
<p style={{ textAlign: 'center' }}>Loader...</p>
}
}发布于 2017-10-10 06:33:01
下面的解决方案对我有效,希望这能解决你的问题。
class News extends Component {
static defaultProps = {
postList: {apiData: [], total: '0'},
};
componentDidMount() {
this.props.getPostListData(this.props.lang, null, this.props.category);
}
props: {
postList: {apiData: Array<Content>, total: string},
getPostListData: Function,
};
render() {
const { postList } = this.props;
let renderNewsCards;
if ((postList.apiData) && Object.keys(postList.apiData).length > 0){
renderNewsCards = (
<NewsCards ... />
);
} else {
renderNewsCards = <p style={{ textAlign: 'center' }}>Loader...</p>;
}
...https://stackoverflow.com/questions/46379467
复制相似问题