Reactjs 在React中,如何将componentDidMount应用于此类组件?
我有一份申请。我有一个这样构造的组件Reactjs 在React中,如何将componentDidMount应用于此类组件?,reactjs,function,components,render,Reactjs,Function,Components,Render,我有一份申请。我有一个这样构造的组件 const AddressInput = (props) => { const classes = useStyles(); const { disabled, error, location, onClear, placeholder, setLocation, showMap, value } = props; useEffect(() => { console.log("use effect 1 ...");
const AddressInput = (props) => {
const classes = useStyles();
const { disabled, error, location, onClear, placeholder, setLocation, showMap, value } = props;
useEffect(() => {
console.log("use effect 1 ...");
if (value && placesRef?.current) {
placesRef.current.setVal(value);
if (zoom === 0) {
setZoom(16);
}
}
}, [placesRef, value, disabled, zoom]);
useEffect(() => {
console.log("use effect 2 ...");
if (location) {
if (zoom === 0) {
setZoom(16);
}
if (location.lat !== position[0]) {
setPosition([location.lat, location.lng]);
}
}
}, [location, zoom, position]);
useEffect(() => {
console.log("use effect 3 ...");
console.log("setting " + inputId + " to :" + placeholder);
if (document.getElementById(inputId)) {
document.getElementById(inputId).value = placeholder;
}
}, [])
...
console.log("after use effect:");
console.log(placeholder);
return (
<div style={error ? { border: "solid red" } : {}}>
...
</div>
);
};
export default AddressInput;
constaddressinput=(props)=>{
const classes=useStyles();
const{disabled,error,location,onClear,占位符,setLocation,showMap,value}=props;
useffect(()=>{
控制台日志(“使用效果1…”);
if(值和位置ref?.current){
placesRef.current.setVal(值);
如果(缩放==0){
setZoom(16);
}
}
},[placesRef,value,disabled,zoom]);
useffect(()=>{
日志(“使用效果2…”);
如果(位置){
如果(缩放==0){
setZoom(16);
}
if(location.lat!==位置[0]){
设置位置([location.lat,location.lng]);
}
}
},[位置、缩放、位置];
useffect(()=>{
日志(“使用效果3…”);
log(“将“+inputId+”设置为“+placeholder”);
if(document.getElementById(inputId)){
document.getElementById(inputId).value=占位符;
}
}, [])
...
日志(“使用后效果:”);
console.log(占位符);
返回(
...
);
};
导出默认地址输入;
我想在组件渲染后执行一些代码。通常我可以使用componentDidMount,但我不确定当组件像上面那样构造时如何应用它。因为您使用的是纯功能组件,所以可以使用
useEffect
钩子(从React v16.8开始):
import React,{useffect}来自“React”;
常量地址输入=(道具)=>{
const classes=useStyles();
const{disabled,error,location,onClear,占位符,setLocation,showMap,value}=props;
useffect(()=>{
//你的代码在这里
},[])//空数组的行为类似于功能组件中的'componentDidMount()'
返回(
...
);
};
导出默认地址输入;
您可以在此处阅读有关useffect
的更多信息:
它不工作了。我对我的问题进行了编辑,以包含您的问题。我还有其他的“useffect”语句,但实际上没有一个被调用。我看到的唯一console.log是在声明useffects之后调用的“after use effect:”消息。我是否实现了您建议的wya?请检查您的
包.json
,并确保您使用的是react@16.8.0
和反应-dom@16.8.0
或更高版本!