【发布时间】:2021-05-12 15:44:16
【问题描述】:
如何在不创建类扩展反应组件的情况下声明 componentDidMount?例如 render() 用 react-dom 包声明,也许是存在另一个 componentDidMount 包?
class App extends Component {
constructor(){
// do something
}
componentDidMount(){
// js code must run after page loaded
}
render(){
return(
<div className="app">
</div>
);
}
}
export {App};
与组件构造函数()相同
const App = () => {
// constructor and componentDidMount does not work here
// js code must run after page loaded
return (
<div className="app">
</div>
);
};
export {App};
【问题讨论】:
-
另一种不使用“扩展组件”来编写 React 组件的方法是使用 React Hooks。您可以在其中编写类似于第二个示例的功能组件,而无需构造函数或 componentDidMount()。 reactjs.org/docs/hooks-intro.html。据我所知,如果不使用“扩展组件”,就无法使用这些功能
-
这是在reactjs.org/docs/hooks-effect.html 中回答的。