我有一个React 16应用程序。我有一个这样构造的组件...
const AddressInput = (props) => {
const classes = useStyles();
const { disabled, error, location, onClear, placeholder, setLocation, showMap, value } = props;
return (
<div style={error ? { border: "solid red" } : {}}>
...
</div>
);
};
export default AddressInput;
我想在组件渲染后执行一些代码。通常我可以使用componentDidMount,但是我不确定在像上面那样构造组件时如何应用它。
由于您使用的是纯功能组件,因此可以使用useEffect
钩子(从React v16.8开始):
import React, { useEffect } from "react";
const AddressInput = (props) => {
const classes = useStyles();
const { disabled, error, location, onClear, placeholder, setLocation, showMap, value } = props;
useEffect(() => {
// your code here
}, []) // empty array acts like `componentDidMount()` in a functional component
return (
<div style={error ? { border: "solid red" } : {}}>
...
</div>
);
};
export default AddressInput;
您可以在此处阅读有关useEffect
的更多信息:https://reactjs.org/docs/hooks-effect.html