【问题标题】:Can Anyone Help me CONVERT Class Component To Functional Component谁能帮我将类组件转换为功能组件
【发布时间】:2021-10-14 17:53:37
【问题描述】:

我正在尝试将类组件转换为函数组件,但没有成功。这是我要转换的类组件:

constructor(props) {
    super(props);
    this.state = {
      address: '',

      showingInfoWindow: false,
      activeMarker: {},
      selectedPlace: {},

      mapCenter: {
        lat: 49.2827291,
        lng: -123.1207375,
      },
    };
  }

  handleChange = (address) => {
    this.setState({ address });
  };

  handleSelect = (address) => {
    this.setState({ address });
    geocodeByAddress(address)
      .then((results) => getLatLng(results[0]))
      .then((latLng) => {
        console.log('Success', latLng);

        // update center state
        this.setState({ address });
        this.setState({ mapCenter: latLng });
      })
      .catch((error) => console.error('Error', error));
  };

这是我失败的尝试:

const Location = () => {
  const [address, setAddress] = useState('')
  const [showingInfoWindow, setShowingInfoWindow] = useState(false)
  const [activeMarker, setActiveMarker] = useState({})
  const [selectedPlace, setSelectedPlace] = useState({})
  const [mapCenter, setMapCenter] = useState({lat: 49.2827291, lng: -123.1207375})


  handleChange = (address) => {
    this.setState({ address });
  };

  handleSelect = (address) => {
    this.setState({ address });
    geocodeByAddress(address)
      .then((results) => getLatLng(results[0]))
      .then((latLng) => {
        console.log('Success', latLng);

        // update center state
        this.setState({ address });
        this.setState({ mapCenter: latLng });
      })
      .catch((error) => console.error('Error', error));
  };
  
    return (

【问题讨论】:

  • 这甚至不是一个完整的类组件。您能否分享完整的示例以及您尝试转换为功能组件的尝试,即使它不起作用,也可以。尝试还包括有关不工作和/或您遇到的任何错误的详细信息。
  • 我没有任何错误也可以显示我的尝试,请稍等,我也可以不发送完整的代码,这是我唯一需要转换的部分,我可以做剩下的谢谢!
  • 希望你能理解
  • 对不起,我说我还很新
  • this.setState({ address }); 转换为 setAddress(address) 以便类型匹配。对其他状态和更新程序执行类似操作。

标签: javascript reactjs react-hooks


【解决方案1】:

这是您的组件的外观。

function Compo() {
  const [address, setAddress] = useState("");
  const [showingInfoWindow, setShowingInfoWindow] = useState(false);
  const [activeMarker, setActiveMarker] = useState({});
  const [selectedPlace, setSelectedPlace] = useState({});
  const [mapCenter, setMapCenter] = useState({lat: 49.2827291, lng: -123.1207375});

  const handleChange = (address) => {
    setAddress(address);
  };
  const handleSelect = (address) => {
    setAddress(address);
    geocodeByAddress(address)
      .then((results) => getLatLng(results[0]))
      .then((latLng) => {
        console.log("Success", latLng);

        // update center state
        setAddress(address);
        setMapCenter(latLng);
      })
      .catch((error) => console.error("Error", error));
  };

  return (...);
}

【讨论】:

    【解决方案2】:

    这看起来像你的类组件的功能组件。很可能您的 componentDidMount 将使用 useEffect() 挂钩更改,状态将使用 useState() 定义。

    function YouClassName(props){
    const [address,setAddress] = useState('');
    const [showingInfoWindow,setshowingInfoWindow] = useState(false);
    const [activeMarker,setactiveMarker] = useState({});
    const [selectedPlace,setselectedPlace] = useState({});
    const [mapCenter,setmapCenter] = useState({});
       
    useEffect(async ()=>{
    setmapCenter({lat: 49.2827291,lng: -123.1207375})
    },[])
    
      const handleChange = (address) => {
        //this.setState({ address });
         setAddress( address ); //Replace everywhere like this
      };
    
      const handleSelect = (address) => {
        setAddress( address );
        geocodeByAddress(address)
          .then((results) => getLatLng(results[0]))
          .then((latLng) => {
            console.log('Success', latLng);
    
            // update center state
            setAddress( address ); 
            setmapCenter( latLng );
          })
          .catch((error) => console.error('Error', error));
      };
    return (
        <div >
           //Your HTML content goes
        </div>
      )
    }
    

    您的函数组件将仅返回 html,而不是渲染。 您可以在 React 指南中查看钩子以获得更多帮助。

    谢谢

    【讨论】:

    • 我没有用 set 方法替换所有 this.state,你可以自己做,除了让我知道是否有任何错误。顺便说一句不是问题。谢谢
    • 尝试更改并告诉我是否有任何错误我认为您应该自己尝试一下:)
    • 顺便说一句,你能告诉我哪个是最佳实践……最佳答案还是你的答案?我总是喜欢检查哪种方法更好
    • 如果一切顺利,请给它一个大拇指。 :)
    • @Sanjeev_gupta2812 this.setState 在功能组件中?
    猜你喜欢
    • 2020-02-08
    • 2020-08-26
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多