首页 > 解决方案 > 可以在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>
         )
      }
   }

我怎么解决这个问题。帮我。

标签: reactjsdjangoaxiosstate

解决方案


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
        });        
    }

推荐阅读