在React的功能组件中,有方法通过钩子来模拟componentDidMount吗?
当前回答
关于钩子内异步函数的信息:
效果回调是同步的,以防止竞争条件。把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
其他回答
对于钩子的稳定版本(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的官方反应页面
在功能组件上没有componentDidMount,但是React Hooks提供了一种方法,可以通过使用useEffect钩子来模拟行为。
将一个空数组作为第二个参数传递给useEffect(),以仅在挂载时运行回调。
请阅读有关useEffect的文档。
function ComponentDidMount() { const [count, setCount] = React.useState(0); React.useEffect(() => { console.log('componentDidMount'); }, []); return ( <div> <p>componentDidMount: {count} times</p> <button onClick={() => { setCount(count + 1); }} > Click Me </button> </div> ); } ReactDOM.render( <div> <ComponentDidMount /> </div>, document.querySelector("#app") ); <script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script> <div id="app"></div>
componentDidMount()的等效钩子是
useEffect(()=>{},[]);
希望这对你有帮助。
在react钩子中没有完全等价的componentDidMount。
根据我的经验,react钩子在开发时需要不同的心态,一般来说,你不应该将它与componentDidMount等类方法进行比较。
尽管如此,还是有一些方法可以使用钩子来产生与componentDidMount类似的效果。
解决方案1:
useEffect(() => {
console.log("I have been mounted")
}, [])
解决方案2:
const num = 5
useEffect(() => {
console.log("I will only run if my deps change: ", num)
}, [num])
方案三(带功能):
useEffect(() => {
const someFunc = () => {
console.log("Function being run after/on mount")
}
someFunc()
}, [])
解决方案4 (useCallback):
const msg = "some message"
const myFunc = useCallback(() => {
console.log(msg)
}, [msg])
useEffect(() => {
myFunc()
}, [myFunc])
解决方案5(变得有创意):
export default function useDidMountHook(callback) {
const didMount = useRef(null)
useEffect(() => {
if (callback && !didMount.current) {
didMount.current = true
callback()
}
})
}
值得注意的是,只有当其他解决方案都不适合您的用例时,才应该真正使用解决方案5。如果你决定你需要解决方案5,那么我建议使用这个预先制作的钩子use-did-mount。
来源(更多细节):在react钩子中使用componentDidMount