componentdidmount - 道具类型验证
componentdidmount - prop-types validation
感谢您的宝贵时间。
Noob React 问题...我知道 componentDidMount 会在第一次渲染组件后触发,这就是我收到的 prop-types
eslint 错误被触发的原因。但是我不确定您将如何解决此问题并添加验证,propTypes 验证会在 getArticles()
函数之前触发,因此如果我声明一个 propTypes 它 returns undefined ... 因为文章直到之后才被定义第一个渲染器和 componentDidMount 被称为...已经进行了很好的挖掘,但看不到我认为是常见问题的简单解决方案??
问题 - 你如何验证尚未获取的道具。
class ArticlesList extends Component {
componentDidMount() {
this.props.getArticles();
}
render() {
return this.props.articles.map(({ id, date, heading, body }) => (
<Article key={id} date={date} heading={heading} body={body} />
));
}
}
const mapStateToProps = (state) => {
return { articles: state.articles };
};
export default connect(mapStateToProps, { getArticles })(ArticlesList);
如果您已将 isRequired
添加到您的道具验证中,例如 PropTypes.array.isRequired
,您只会遇到未定义道具的问题。考虑到这一点,您只需要正确定义您的 propType:
ArticlesList.propTypes = {
articles: PropTypes.array,
}
解构 componentDidMount 即
componentDidMount() {
{ getArticles } = this.props;
getArticles();
}
并添加
ArticlesList.propTypes = {
getArticles: PropTypes.func,
articles: PropTypes.array,
};
感谢您的宝贵时间。
Noob React 问题...我知道 componentDidMount 会在第一次渲染组件后触发,这就是我收到的 prop-types
eslint 错误被触发的原因。但是我不确定您将如何解决此问题并添加验证,propTypes 验证会在 getArticles()
函数之前触发,因此如果我声明一个 propTypes 它 returns undefined ... 因为文章直到之后才被定义第一个渲染器和 componentDidMount 被称为...已经进行了很好的挖掘,但看不到我认为是常见问题的简单解决方案??
问题 - 你如何验证尚未获取的道具。
class ArticlesList extends Component {
componentDidMount() {
this.props.getArticles();
}
render() {
return this.props.articles.map(({ id, date, heading, body }) => (
<Article key={id} date={date} heading={heading} body={body} />
));
}
}
const mapStateToProps = (state) => {
return { articles: state.articles };
};
export default connect(mapStateToProps, { getArticles })(ArticlesList);
如果您已将 isRequired
添加到您的道具验证中,例如 PropTypes.array.isRequired
,您只会遇到未定义道具的问题。考虑到这一点,您只需要正确定义您的 propType:
ArticlesList.propTypes = {
articles: PropTypes.array,
}
解构 componentDidMount 即
componentDidMount() {
{ getArticles } = this.props;
getArticles();
}
并添加
ArticlesList.propTypes = {
getArticles: PropTypes.func,
articles: PropTypes.array,
};