reactjs - 从窗口获取路径名并将其存储在状态中以在 fetch 函数中使用
问题描述
我有以下功能:
fetchData = () => {
fetch('/api/customerNodes' + this.state.number)
.then(response => response.text())
.then(message => {
this.setState({responseText: message});
});
};
如果我将浏览器指向localhost:3000/1234
并且我想获得 1234 的路径名,我会做这样的事情。const num = window.location.pathname;
我面临的问题是我无法将该值设置为状态。
componentDidMount() {
const num = window.location.pathname;
this.setState({ number: num });
console.log(this.state.number);
//setInterval(this.fetchData, 250);
}
console.log
是空的。
我究竟做错了什么?
解决方案
使用回调函数this.setState
const num = window.location.pathname;
this.setState({ number: num }, () => {
console.log(this.state.number, 'number');
});
setState() 通常是异步的,这意味着在您控制台记录状态时,它还没有更新。通过将日志放在 setState() 方法的回调中,它会在状态更改完成后执行。
推荐阅读
- ag-grid - 禁用最后一行的排序
- tableau-api - 基于计算的固定 LOD 表达式
- java - Maven Shade 重定位类调用非重定位类
- c# - 更新后设置不同?无法更改语言版本
- multilingual - Shopware 多语言类别
- amazon-redshift - 如何在带有 Redshift 的 SQL Workbench/J 中使用保存点?
- python - 仅当任何字符串的乞求在数据集中针对某些值不出现多次时才保留字符串行
- r - 将图例添加到具有 2 y 轴的图中
- android - 使用 gradle build application 构建 AOSP 项目
- laravel - laravel replicate() 方法和计算的数据库列