【发布时间】:2017-09-23 12:15:01
【问题描述】:
我正在使用 Flow v.0.52 输入我的 React 应用程序,但我在正确分配默认道具时遇到问题。
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
P.S. Link 归档News.jsx
【问题讨论】:
-
尝试将
static defaultProps = {更改为News.defaultProps = { -
@jsw324 不,它不起作用 - ESLint 正在大喊大叫
error Parsing error: Unexpected token -
根据错误,听起来
postList.apiData是未定义的,而不是postList。似乎postList是从其他地方作为道具传递的(redux 连接?)并且它没有apiData属性 -
@john-shammas 是的,
postList.apiData来自 Redux 商店的道具。因为 reducer 中的初始状态是{},因此postList.apiData是未定义的,postlist本身是 {}。但是关于默认道具,道具来自哪里真的很重要吗? -
@TarasYaremkiv 如果 redux 传入
{},那么你的默认 prop 将永远不会被使用