[英]React Component not support lifecycle methods?
如何在下面的函數中使用生命周期方法,例如ComponentDidMount?
var React = require('react');
module.exports = function SectionalSquareComponent(props) {
return (
<div .....
如果要使用生命周期函數,則需要擴展React.Component類。 如@xadm所述,您不能使用功能組件和生命周期掛鈎。
按照您的問題使用ES5語法,看起來可能像這樣:
var createReactClass = require('create-react-class');
module.exports = createReactClass({
componentDidUpdate: function(prevProps, prevState) {
},
render: function() {
return (<div>...</div>);
}
});
正如其他人所說,如果您想加入生命周期方法,則需要使用react.component 。
如果您完全專注於功能組件,那么一個有趣的替代方法是使用recompose.lifecycle方法,因此您可以這樣做(來自docs):
const PostsList = ({ posts }) => (
<ul>{posts.map(p => <li>{p.title}</li>)}</ul>
)
const PostsListWithData = lifecycle({
componentDidMount() {
fetchPosts().then(posts => {
this.setState({ posts });
})
}
})(PostsList);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.