简体   繁体   English

React无法从API访问Json Resposne

[英]React Unable to Access Json Resposne from API

In my website on login,i get a confirmation and a token which i need to store and pass as a property throughout all the pages.I am able to receive the token,but i am unable to store the value for the token and store it as a state value. 在登录后的网站上,我得到一个确认和一个令牌,我需要将其存储并作为属性传递给所有页面。我能够接收该令牌,但是我无法存储该令牌的值并将其存储作为状态值。

Here is the code i have tried so far. 这是我到目前为止尝试过的代码。

import React from 'react'
import ReactDOM from 'react-dom'
import {Login_Submit_style,Login_button_style,Login_text_field_style,
password_style,para_login_style} from './style'

import Supers from 'superagent'

class Login extends React.Component
{
  constructor(props)
  {
    super(props);
    this.state={username:'',password:''}
    this.Login_data_password=this.Login_data_password.bind(this)
    this.Login_data_username=this.Login_data_username.bind(this)
    this.MainRedirect=this.MainRedirect.bind(this)
    this.api_call_login=this.api_call_login.bind(this)
  }

Login_data_username(e)
{
  this.setState({username:e.target.value})
}

Login_data_password(password)
{
  this.setState({password:password.target.value})
}

MainRedirect()
{
  window.location = '/main';
}

api_call_login()
{
  Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
  .send({'username':this.state.username,'password':this.state.password})
  .then(response => response.json())
  .then(responseData=>{
    console.log(responseData);
  })
    }



render()
{
  return(
    <div style={{background:'yellow'}}>
      <div>
        <h1 style={{marginLeft:550}}>Login Page</h1>
        <div>
          <p style={para_login_style}><b>Username</b></p>
          <input type="text" style={Login_text_field_style} onChange={this.Login_data_username}/>
          <h2>{this.state.username}</h2>
        </div>
        <div>
          <p style={para_login_style} ><b>Password</b></p>
          <input type="password" style={password_style} onChange={this.Login_data_password}/>
        </div>
        <div>
          <button style = {Login_Submit_style} onClick={this.api_call_login}> Log in </button>
        </div>
      </div>
    </div>
  )
}
}

This is the Format in which i get the response: {"Successful_Login": "True", "token": "d278f30445aa0c37f274389551b4faafee50c1f2"} 这是我得到响应的格式:{“ Successful_Login”:“ True”,“ token”:“ d278f30445aa0c37f274389551b4faafee50c1f2”}

So ideally i would like to store the values for both the keys returned from the json output.Adn when i use response.body,i am able to get the data in the above format. 所以理想情况下,我想存储从json output.Adn返回的两个键的值,当我使用response.body时,我能够以上述格式获取数据。

I don't know if this will be helpful to you, but I'll try. 我不知道这是否对您有帮助,但我会尽力的。

Things like XHR calls from a browser to an API are done asynchronously. 从浏览器到API的XHR调用等操作都是异步完成的。 What you get back is a promise that will execute a function you give it when the call to the API is completed. 您得到的回报是一个承诺,它将在对API的调用完成后执行您提供的功能。 Your code rightly has a callback function. 您的代码正确地具有回调函数。

However, I don't think that callback function can call setState, because I think (I might be wrong) React wouldn't like it. 但是,我不认为回调函数可以调用setState,因为我认为(我可能是错误的)React不会喜欢它。

I use Redux for React as a way of storing stuff that the rest of the app can just grab when it needs it. 我将Redux用于React作为一种存储内容的方法,该应用程序的其余部分可以在需要时抓取。 Better still, Redux is integrated into React in such a way that whenever this central database is updated, any component that pulls in a piece of data from it (via props) gets updated (re-rendered) automatically. 更好的是,Redux以这样的方式集成到React中:无论何时更新此中央数据库,任何从中提取数据(通过props)的组件都将自动更新(重新呈现)。

I think I should point you to the documentation for Redux for more information. 我想我应该为您提供有关Redux的文档,以获取更多信息。 There are alternatives to Redux, too. Redux也有替代方案。

Good luck, and ask more questions if you get stuck. 祝你好运,如果遇到困难,请问更多问题。

In order to set a new state with the values from a json response, I ideally call this.setState right in your promise response. 为了使用json响应中的值设置新状态,理想情况下,我会在您的promise响应中正确地调用this.setState。

api_call_login()
{
  Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
  .send({'username':this.state.username,'password':this.state.password})
  .then(response => response.json())
  .then(responseData=>{
    this.setState({ 
      Successful_Login: responseData.Successful_Login,
      token: responseData.token
  })
}

state will be updated when response arrives. 响应到达时,状态会更新。

If possible try to use lowercase or camelCase to your keys. 如果可能的话,请尝试使用小写或camelCase作为密钥。

It would be great if you could post link where we can see what exactly is going on, but the way I understand this you would have to add .set('Accept', 'application/json') in your request to get correct json. 如果您可以在我们可以看到实际情况的链接上发布链接,那就太好了,但是按照我的理解,您必须在请求中添加.set('Accept', 'application/json')才能获取正确的json 。 So, your code should be like: 因此,您的代码应类似于:

Supers.post('http://127.0.0.1:8000/user_ops/user_login/')
      .send({'username':this.state.username,'password':this.state.password})
      .set('Accept', 'application/json')
      .then(response => response.json())
      .then(responseData=>{
            console.log(responseData);
})

Since I cannot test, you would have to look if it works. 由于我无法测试,因此您必须查看它是否有效。 Alternatively, I would suggest you to try using superagent 另外,我建议您尝试使用超级代理

Let me know if it helps! 让我知道是否有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM