javascript - setState() 不会立即改变状态
问题描述
我有一个父组件,它使用 get 请求来检索 JWT 令牌,然后将该令牌作为道具传递给子组件。该令牌在另一个获取请求中传递以授权和检索数据。在执行该获取请求的方法上,我在请求成功后使用 setState 来更新空数组的状态。问题是它落后了,因为 setState 没有足够快地改变状态并且数组保持为空。我正在尝试将该数组值作为道具传递给子组件。任何帮助表示赞赏。
App.js - 父组件
class App extends Component {
constructor(props) {
super(props);
this.state = {
token: '',
};
this.getToken = this.getToken.bind(this);
}
getToken() {
fetch('https://login-cmhmanagement.itg.cct-pubweb.com/nofapsaml', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json; charset=utf-8',
},
})
.then(response => response.json())
.then(data => {
this.setState({ token: data });
});
}
componentDidMount() {
this.getToken();
}
render() {
const { token } = this.state;
return (
<div className="app-container">
<Navigation
token={token}
/>
</div>
);
}
导航.Js
export default class Navigation extends Component {
constructor(props) {
super(props);
this.state = {
user: [],
value: '',
};
this.getUserData = this.getUserData.bind(this);
}
componentDidMount() {
setTimeout(() => {
this.getUserData();
}, 2000);
}
getUserData() {
const { token } = this.props;
let auth = token;
fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${auth}`,
},
})
.then(response => response.json())
.then(result => {
this.setState({ user: result });
});
}
render() {
const { user } = this.state;
return (
<SideBarStyled>
<UserInfo
authorizedLots={user.authorizeLots}
/>
</SideBarStyled>
);
}
解决方案
你永远不应该依赖超时,因为你永远不知道网络延迟。
而是像下面这样使用:-
导出默认类导航扩展组件 {
constructor(props) {
super(props);
this.state = {
user: [],
value: '',
};
this.getUserData = this.getUserData.bind(this);
}
componentDidUpdate(prevProps) {
if(prevProps.token !== this.props.token){
this.getUserData();
}
}
getUserData() {
const { token } = this.props;
let auth = token;
fetch(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${auth}`,
},
})
.then(response => response.json())
.then(result => {
this.setState({ user: result });
});
}
render() {
const { user } = this.state;
return (
<SideBarStyled>
<UserInfo
authorizedLots={user.authorizeLots}
/>
</SideBarStyled>
);
}
推荐阅读
- c++ - Qt:更新 QString 时自动生成的代码失败
- c++ - 如何将值分配给地图<地图
, 布尔 >? - google-cloud-platform - 使用自定义网络将虚拟磁盘导入 Google Cloud
- java - 非短路算子
- sql - 如何连接具有不同字段的两个表?
- sql - 列模式上的 Spark SQL 区分大小写过滤器
- hacklang - How to define empty dict
in hacklang - docker - Docker Toolbox 镜像操作系统“windows”不能在这个平台上使用
- r - 如何将 ggplot2 函数转换为简单的 XY 方程
- javascript - Javascript测验不验证答案