javascript - 通过道具将功能从类组件编辑状态传递到基于功能的组件不起作用
问题描述
我有一个反应前端,我的大多数组件都是基于类的组件,但碰巧这些类组件中的一个组件必须是一个功能组件,所以我目前有一个带有基于类的组件的功能组件。
在功能组件内部,我有一个触发 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 ,所以我不知道问题可能是什么。我一直试图弄清楚这一点,我完全被难住了。有谁知道为什么会发生这个错误?
解决方案
then
应该有一个回调试试这个:
const FunctionComponent = (props) => {
const fetchSomething = () => {
fetch('fetch is made here and is successful')
.then(()=>props.setSubscription({value1: 1, value2: 2}))
}
}
推荐阅读
- angular - 同一页面中的 Angular mqny 加载器
- php - Json 不存储输入文件的值
- eclipse - “Coverage As”选项不考虑 TestNG 运行/调试首选项
- flutter - 当我从 android studio 创建颤振项目时出错
- go - go: 找不到主模块;见“去帮助模块”
- vue.js - Vue3、Typescript 和 Eslint 引发:“解析错误:'}' 预期”
- c++ - 如何在 C++ 中的不同页面上显示文件内容?
- swift - 使用 macOS Big Sur 版本 11.1 时收到安装 Firestore pod 的错误消息
- html - 仅使用 CSS,如果 ID 存在,如何隐藏父子元素?
- javascript - 将来自 API 的错误显示到前端