reactjs - 可以在reactjs中用axios设置字符串数据状态
问题描述
我想将从 API 接收到的字符串保存在状态中,但它不能。首先,我编写了如下 Python 代码,它返回用户名的前 3 个字母(输入每个用户名,前三个字母指定其类型)。这是 Django(python) 代码:
from django.shortcuts import redirect, render
from rest_framework.views import APIView
from rest_framework.response import Response
class usertype(APIView):
def get(self,request,format=None):
try:
user=request.user
except:
raise ValueError('error')
return Response({
'username':user.username[:3],
})
然后我编写此代码以响应单独的仪表板:
import React, { Component } from 'react'
import { render } from 'react-dom';
import DashboardS from './Students/DashboardS';
import DashboardT from './Teachers/DashboardT';
import axios from 'axios';
const api=axios.create({
baseURL:'http://127.0.0.1:8000/accounts/usertype/'
})
export default class App extends Component {
constructor(props){
super(props);
this.state={
usertype:'',
showS:false,
showT:false,
}
this.showDash=this.showDash.bind(this);
this.getusertype=this.getusertype.bind(this);
}
componentDidMount(){
this.getusertype();
this.showDash();
}
getusertype(){
api.get('/').then(res=>{
this.setState({
usertype:res.data.username,
});
console.log(res.data.username); // out is std for stduent user
});
}
showDash(){
switch(this.state.usertype){
case "std":
this.setState({
showS:true,showT:false,
})
break;
case "tcr":
this.setState({
showS:false,showT:true,
})
break;
}
}
render() {
return (
<div>
{this.state.showS && <DashboardS/>}
{this.state.showT && <DashboardT/>}
</div>
)
}
}
我怎么解决这个问题。帮我。
解决方案
API 调用是异步操作,这意味着其他代码将继续执行,直到收到响应。showDash
在将用户类型设置为状态之前调用您的函数。更新您的代码以showDash
像这样调用
getusertype(){
api.get('/').then(res=>{
this.setState({
usertype:res.data.username,
},()=>{
this.showDash();
});
console.log(res.data.username); // out is std for stduent user
});
}
推荐阅读
- mongodb - 如何使用 $lookup 获取 mongodb 中外部字段的计数?
- angular9 - Angular 9 ng-bootstrap 6.1 模态组件打开方法不起作用
- python - python中具有许多参数的函数
- bash - Bash 计数未注释的行并使用文件名写入输出
- firebase - 如何使用颤振将我在firestore中的所有文档返回到列表中
- c# - 箭头键输入与专注于对象
- python - 在python中将列表变成数组数组
- scala.js - scalajs:从 window.location 获取 searchParams(解析查询字符串)
- ios - 如何录制视频并将其与 AVPlayer 同步?
- vuejs2 - 因为不做动态变化,v-mask,vuejs