在React的功能组件中,有方法通过钩子来模拟componentDidMount吗?
当前回答
对于钩子的稳定版本(React version 16.8.0+)
对于componentDidMount
useEffect(() => {
// Your code here
}, []);
对于componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
对于componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
在这种情况下,你需要将你的依赖传递到这个数组中。假设有一个这样的状态
const [count, setCount] = useState(0);
当count增加时,你想重新渲染你的函数组件。然后你的useEffect应该看起来像这样
useEffect(() => {
// <div>{count}</div>
}, [count]);
这样,每当你的计数更新你的组件将重新呈现。希望这对你有所帮助。
其他回答
对于钩子的稳定版本(React version 16.8.0+)
对于componentDidMount
useEffect(() => {
// Your code here
}, []);
对于componentDidUpdate
useEffect(() => {
// Your code here
}, [yourDependency]);
对于componentWillUnmount
useEffect(() => {
// componentWillUnmount
return () => {
// Your code here
}
}, [yourDependency]);
在这种情况下,你需要将你的依赖传递到这个数组中。假设有一个这样的状态
const [count, setCount] = useState(0);
当count增加时,你想重新渲染你的函数组件。然后你的useEffect应该看起来像这样
useEffect(() => {
// <div>{count}</div>
}, [count]);
这样,每当你的计数更新你的组件将重新呈现。希望这对你有所帮助。
useEffect()钩子允许我们实现componentDidMount功能,componentDidUpdate componentWillUnMount功能。
useEffect()的不同语法允许实现上述每一种方法。
我)componentDidMount
useEffect(() => {
//code here
}, []);
(二)componentDidUpdate
useEffect(() => {
//code here
}, [x,y,z]);
//where x,y,z are state variables on whose update, this method should get triggered
3) componentDidUnmount
useEffect(() => {
//code here
return function() {
//code to be run during unmount phase
}
}, []);
你可以查看官方react网站获取更多信息。hook的官方反应页面
虽然公认的答案是可行的,但不建议使用。当你有多个状态并且你和useEffect一起使用它时,它会警告你是否将它添加到依赖数组或者根本不使用它。
它有时会导致问题,可能会产生不可预测的输出。因此,我建议您花点精力将函数重写为类。有很少的变化,您可以将一些组件作为类,一些作为函数。您没有义务只使用一种约定。
以这个为例
function App() {
const [appointments, setAppointments] = useState([]);
const [aptId, setAptId] = useState(1);
useEffect(() => {
fetch('./data.json')
.then(response => response.json())
.then(result => {
const apts = result.map(item => {
item.aptId = aptId;
console.log(aptId);
setAptId(aptId + 1);
return item;
})
setAppointments(apts);
});
}, []);
return(...);
}
and
class App extends Component {
constructor() {
super();
this.state = {
appointments: [],
aptId: 1,
}
}
componentDidMount() {
fetch('./data.json')
.then(response => response.json())
.then(result => {
const apts = result.map(item => {
item.aptId = this.state.aptId;
this.setState({aptId: this.state.aptId + 1});
console.log(this.state.aptId);
return item;
});
this.setState({appointments: apts});
});
}
render(...);
}
这只是举个例子。因此,让我们不要谈论代码的最佳实践或潜在问题。两者的逻辑相同,但后者只能按预期工作。此时,你可能会获得componentDidMount功能和useEffect,但随着应用程序的发展,你可能会面临一些问题。所以,与其在那个阶段重写,不如在早期就重写。
此外,面向对象并不是那么糟糕,如果面向过程编程就足够了,我们就永远不会有面向对象编程了。有时会很痛苦,但更好(技术上来说。暂且把个人问题放在一边)。
关于钩子内异步函数的信息:
效果回调是同步的,以防止竞争条件。把async函数放在里面:
useEffect(() => {
async function fetchData() {
// You can await here
const response = await MyAPI.getData(someId);
// ...
}
fetchData();
}, [someId]); // Or [] if effect doesn't need props or state
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
请访问这个官方文件。很容易理解最新的方式。
https://reactjs.org/docs/hooks-effect.html
推荐文章
- 这个“react-scripts eject”命令是做什么的?
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类