【问题标题】:ReactJS - How can I transform a Class Component withsSide-effects of combined state updates to a Functional ComponentReactJS - 如何将具有组合状态更新的副作用的类组件转换为功能组件
【发布时间】:2020-11-10 23:12:00
【问题描述】:

我正在使用ftw-hourly,特别是on this file 我想将其转换为一个功能组件(由于我需要对 Mapbox 进行一些状态管理 - 我希望从 Mapbox 获取位置并使用从搜索中检索到的信息填充表单输入字段)。

但是,在将组件转换为功能组件时,我在弄清楚我应该如何处理 getInitialValues 时遇到了一些问题。

我的任务可以完成吗?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    是函数式组件没有方法的问题吗?如果是这样,您可以在其他函数中创建函数(函数组件中的函数),如下所示:

    import React from 'react';
    
    const MyFunctionalComponent = (props) => {
    
        const getInitialValues = function(){
            ...rest of function...
        }
    
        return ( ... );
    };
    

    然后,您可以调用getInitialValues() 而不是this.getInitialValues(),以及props 而不是this.props

    【讨论】:

    • 你说得对,丹尼尔。我最终搜索了更多,我为我的getInitialValuesfunction 使用了this 解决方案,并且我使用了const [initialValues, setInitialValues] = useState(getInitialValues);afterwards
    猜你喜欢
    • 2021-02-08
    • 2020-08-26
    • 1970-01-01
    • 2020-05-22
    • 2020-10-17
    • 2021-07-21
    • 2017-01-16
    • 2020-12-04
    • 2021-02-21
    相关资源
    最近更新 更多