[英]alternatives to componentDidMount....Axios?
I have recently done a few API tests for a new job.我最近为一项新工作做了一些 API 测试。 Just receiving data and passing it through.只是接收数据并传递它。 Although I have completed the tasks and it works functionally, the people I walk through it with are not huge fans of componentDidMount.尽管我已经完成了任务并且它可以正常工作,但与我一起走过它的人并不是 componentDidMount 的忠实粉丝。
They do not suggest an alternative?他们不建议替代方案吗? Anyone know why this could be?有谁知道为什么会这样? Is it due to it being async?是因为它是异步的吗?
The new modern way to do it is: useEffect新的现代方法是: useEffect
First some code (from the docs):首先是一些代码(来自文档):
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
At the end-of-the-day, the componentDidMount purpose is to execute something(the side effect) because the component was mounted(the reason or event).归根结底,componentDidMount 的目的是执行某些事情(副作用),因为组件已安装(原因或事件)。
So you can specify array of dependencies (or causes) for re-running like so:因此,您可以像这样指定重新运行的依赖项(或原因)数组:
useEffect(() => {
// ....
}, [someVar]);
so if someVar
changed, the function will re-run.所以如果someVar
改变了,function 将重新运行。
Special use cases are;特殊用例是; omitting this argument, will cause it to run once, on-mount event.省略此参数,将导致它运行一次,即挂载事件。 and specify empty array will cause it to run on each re-render.并指定空数组将导致它在每次重新渲染时运行。
componentWillUnmount
:对于componentWillUnmount
:Just return a function from the inner function like so:只需从内部 function 返回一个 function ,如下所示:
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.