简体   繁体   中英

React - fetch 'message' from Meta-Data element of the response from an Ajax post request

So I have received this response from an Ajax post request (part of the response is shown) where:

Data:
  Meta-Data:
    Topic : "Sign-Up"
    Message : "Already in the System!"
    Response Code : "650"
.
.
.  

how can I fetch the message and show it to user? I was thinking I could do this in React:

    state = {
    username : "John",
    password : "somePass",
    postResponse : null
    }
    axios.post(URL, JSON.stringify({ username : this.state.username , password: this.state.password})
    .then(response => { this.setState({postResponse : response.data}) }

and then in render() I do:

     render(){
let message = null; 
    if (this.state.postResponse){
    message = <p>{this.postResponse.data.meta-data.message}</p> //apparently the dash is breaking the code!
    }
     return(<div> {message} </div>)}

Which doesn't work at all! "it is a part of my code, I hope I've included all necessary parts"

Two things I can see. You had this.postResponse. It should be this.state.postResponse from what I can tell. Also, you need to put “meta-data” into quotes and use brackets to reference it, as shown below.

state = {
    username : "John",
    password : "somePass",
    postResponse : null
    }
    axios.post(URL, JSON.stringify({ username : this.state.username , password: this.state.password})
    .then(response => { this.setState({postResponse : response.data}) }

render(){
  let message = null; 
  if (this.state.postResponse){
    message = <p>{this.state.postResponse[“meta-data”].message}</p>
    }
     return(<div> {message} </div>)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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