reactjs - 在请求模块中设置状态
问题描述
我正在制作一个小型 react.js 应用程序并计划调用两个不同的 API。第一个 API 给了我特定的坐标,然后我将在我的第二个 API 调用中动态使用它。我的计划是通过将坐标保存到请求模块中的状态来保存坐标,但不断收到“this.setState is not a function”。多读一点,我相信我需要让我的请求成为一个胖箭头功能,但还没有成功。关于如何在请求模块中设置状态以及如何动态更新第二个 API 调用的任何想法?感谢所有的帮助!
class App extends Component {
constructor(props) {
super(props);
this.state = {
lat: '',
long: '',
};
}
componentDidMount() {
let request = require('request');
let options1 = {
method: 'GET',
json: true,
url: url1,
headers: {
'content-type': 'application/json',
},
};
request(options1, function (error1, response1, body1) {
if (error1) throw new Error(error1);
this.setState({ lat: response1, long: response1 });
});
let options = {
method: 'GET',
json: true,
url: url,
qs: { lat:`${this.state.lat}` , lng: `${this.state.long}`, dt: '2018-01-24T10:50:52.283Z' },
headers: {
'content-type': 'application/json',
'x-access-token': `${process.env.REACT_APP_UV_API_KEY}`,
},
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(response.body.result.uv);
});
}
render() {
return (
<div>
<header>
<Home />
</header>
</div>
);
}
}```
解决方案
我想指出 this.setState 是以重新渲染为代价的,从我在 render 方法中看到的内容来看,您并不真正依赖 lat, long 进行渲染。因此,最好将其用作常量变量而不是状态变量。
如果你想坚持使用它们作为状态变量,有很多方法可以做到这一点。箭头函数如下所示:
request(options1, (error1, response1, body1) => {
if (error1) throw new Error(error1);
this.setState({ lat: response1, long: response1 });
});
this
需要有正确的工作范围,箭头函数可以解决这个问题。你可以在这里阅读更多
您甚至可以分配this
给另一个变量并在请求中使用它
const self = this;
request(options1, function(error1, response1, body1) {
if (error1) throw new Error(error1);
self.setState({ lat: response1, long: response1 });
});
箭头函数是首选方法。
推荐阅读
- python - QML ComboBox 中的 Python 列表
- c# - 如何打开带有损坏数据的word文档?
- windows - 如何使用通用分析为基于电子的 Windows 应用程序实施 Google Analytics?
- python - Groupby n-largest 基于一列并且有条件地在第二列
- flutter - How can i parse a JSON file with other language(i.e Gujrati in this case) in flutter?
- html - 创建一个覆盖整个屏幕的视频容器
- ios - Juno(iOS 版 Jupyter)指定加载数据集的目录
- java - org.thymeleaf.exceptions.TemplateInputException:模板解析时出错
- java - 如何在 IntelliJ Structural Replace 中将 Java 原语转换为盒装类型
- django-viewflow - 获取进程的当前任务