首页 > 解决方案 > 通过道具将功能从类组件编辑状态传递到基于功能的组件不起作用

问题描述

我有一个反应前端,我的大多数组件都是基于类的组件,但碰巧这些类组件中的一个组件必须是一个功能组件,所以我目前有一个带有基于类的组件的功能组件。

在功能组件内部,我有一个触发 fetch 调用的按钮。在这个 fetch 调用完成后,我希望更新基于类的(父)组件的状态。

我的方法是在基于类的组件(称为 setSubscriptoin)中创建一个函数,用于调整基于类的组件的状态,然后通过 props 将该函数传递给函数式组件,并在 fetch 调用后使用 .then 承诺调用该函数.

但是,似乎当我通过道具传递功能时,功能组件甚至无法检测到该功能,并且出现此错误: Uncaught (in promise) TypeError: e.setSubscription is not a function.

这是重要的代码:

基于类的组件:

class OuterComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {subscription: {}}
    }

    setSubscription(subscription) {
        this.setState({subscription: subscription})
    }

    render() {
        return(
            <Elements>
                <FunctionComponent setSubscription={this.setSubscription.bind(this)}></FunctionComponent>
            </Elements>
        )
    }
}

我想包括元素部分,因为我不确定这是否会影响它。FunctionComponent 包装在 Stripe Elements 提供程序中。不知道为什么那会做任何事情,但我想我应该包括它以防万一。

功能组件:

const FunctionComponent = (props) => {
    const fetchSomething = () => {
        fetch('fetch is made here and is successful')
        .then(response => {
            if (some_condition) {
                props.setSubscription({value1: 1, value2: 2}))
            }
        } 
    }
} 

问题是函数组件甚至不将 props.setSubscription 识别为函数(如错误所示)。

我试过控制台记录 props 变量,它实际上有函数 setSubscription ,所以我不知道问题可能是什么。我一直试图弄清楚这一点,我完全被难住了。有谁知道为什么会发生这个错误?

标签: javascriptreactjsreact-hooksstripe-paymentsreact-props

解决方案


then应该有一个回调试试这个:

const FunctionComponent = (props) => {
    const fetchSomething = () => {
        fetch('fetch is made here and is successful')
        .then(()=>props.setSubscription({value1: 1, value2: 2}))  
    }
}

推荐阅读