reactjs - 无法绑定到导入的函数。错误未定义
问题描述
我目前在导入模块并在反应中使用它时遇到问题。有人问过这个问题,我已经尝试过我读过的答案,但没有。我不确定我做错了什么。
在 App.js 我导入这个:
import { pullProductDetails } from './GetDetails';
在 GetDetails.js 我有这个:
export default pullProductDetails = () => {
this.setState({isLoading: true});
fetch('http://127.0.0.1:8000/product_details/fetch/36')
.then(response => response.json())
.then(json => {
const quantityDetails = json.productQuanties.map((quantityDetail) => {
quantityDetail.selected = false;
quantityDetail.title = "Quantity";
});
this.setState(
{
quantityProduct: [...this.state.quantityProduct, ...json.productQuanties],
isLoading: false,
}, () => this.dropdownCounter()
);
});
}
然后在 app.js 中绑定它,这样我就可以使用“this”
this.pullProductDetails = this.pullProductDetails.bind(this);
错误是它无法将 this 绑定到 undefined,因为 pullProductDetails 是未定义的。
我也试过这个:
export const pullProductDetails = () => {}
以上都不起作用。我需要从我的 App.js 调用 this.pullProductDetails。有任何想法吗?
解决方案
您必须省略作业右侧的 (this)
this.pullProductDetails = pullProductDetails.bind(this);
因为你绑定的函数不是当前组件的函数。pullProductDetails 的定义也不应该是箭头函数,因为在箭头函数中 this 的上下文总是指向函数的定义位置。
获取详细信息.js:
export function pullProductDetails(){
this.setState({isLoading: true});
fetch('http://127.0.0.1:8000/product_details/fetch/36')
.then(response => response.json())
.then(json => {
const quantityDetails = json.productQuanties.map((quantityDetail) => {
quantityDetail.selected = false;
quantityDetail.title = "Quantity";
});
this.setState(
{
quantityProduct: [...this.state.quantityProduct, ...json.productQuanties],
isLoading: false,
}, () => this.dropdownCounter()
);
});
}
在您的主文件中:
import pullProductDetails from './GetDetails';
然后添加构造函数:
constructor(props){
super(props);
this.pullProductDetails = pullProductDetails.bind(this);
}
推荐阅读
- c# - 将自定义标头添加到 HttpRequestHeaders
- xml - 使用 XSLT 基于子属性值删除重复标签
- linux - 结合两个否定的文件检查条件(-f 和 -s)似乎返回不正确的结果
- arrays - 返回数组中数字的总和,忽略数字部分除外
- javascript - 如何在本地存储从 API 检索到的数据并使用 Javascript 以相等的时间间隔更新这些数据?
- ruby-on-rails - 为什么redis返回更多的值而不是计数?
- c# - ASP.NET Core 3 - 带有 Kestrel 和 IIS Express 的 Web.config?
- google-apps-script - 如何显示在特定单元格中运行宏的用户的名称?
- r - 如何计算多个数据帧中值的出现次数
- css - 有没有办法让文本粘在 div“边框”上?