如何在react js中更改helper函数文件中的状态值



我有functions.js文件,它导出了一个我想在许多文件中使用的函数。

functions.js

import { API_URL } from "./index";
export const getData = (skip = 0, params = "") => {
this.setState({
loading: true
});
fetch(`${API_URL}items?limit=5&skip=${skip}${params}`, {
method: "GET",
credentials: "include"
})
.then(res => res.json())
.then(res => {
if (res.result.length > 0) {
let array = [];
res.result.map(item => {
let obj = item.data;
obj = Object.assign({ id: item._id }, obj);
array.push(obj);
});

this.setState({
records: array,
loading: false
});
} else {
this.setState({
next: true,
loading: false,
records: []
});
}
})
.catch(err => {
this.setState({
loading: false
});
});
};

听说这是从API获取数据并设置在状态中的function.js文件,现在,我想在items.js中使用这个函数

items.js

import { getData } from "./../../config/functions";
import React from "react";
class Customers extends React.Component {
constructor(props) {
super(props);
this.getData = getData.bind(this);
}
componentDidMount() {
this.getData();
}

...
}

错误

TypeError:无法读取未定义的属性"setState">

我找到了这个答案如何在reactjs中使用另一个文件中一个组件的状态?但它对我不起作用,所以请帮助我从functions.js文件更改app.js文件状态。

您正试图在箭头函数上重新绑定this,但您无法做到这一点。查看其他SO问题/答案以了解更多详细信息,但这是您的问题。我将编辑这篇文章,并建议用一种更地道的方式在React中写这篇文章。

编辑:好的,我想尽快给你一个答案,这样你就可以解锁自己,并了解更多关于箭头函数和this绑定的信息。

但是,如果您将api请求与组件分离,那么不仅可以修复此问题,还可以显著改进此代码。现在,您正试图在获取数据的函数中设置状态,从而将它们混合在一起。

import { API_URL } from "./index";
export const getData = (skip = 0, params = "") => {
this.setState({
loading: true
});
fetch(`${API_URL}items?limit=5&skip=${skip}${params}`, {
method: "GET",
credentials: "include"
})
.then(res => res.json())
.then(res => {
// no need to declare an array and then push to it,
// that's what map is for. It will return a new array.
return res.result.map(item => {
// can also be written as return { ...item, id: item._id }
return Object.assign({ id: item._id }, obj)
});
});
// no need to catch here, you can do error handling in your component
};

import { getData } from "./../../config/functions";
import React from "react";
class Customers extends React.Component {
constructor(props) {
super(props);
this.fetchData = this.fetchData.bind(this);
}
componentDidMount() {
this.fetchData();
}
fetchData() {
getData()
.then((results) => {
this.setState({
next: results.length === 0,
records: results,
loading: false
});
})
.catch((err) => {
this.setState({ loading: false })
});
}

...
}

最新更新