How to set state of a react component with a specific item from a returned json object?

后端 未结 3 2200
死守一世寂寞
死守一世寂寞 2020-12-21 20:56

This is a follow up question to the previous thread

How to return json data to a react state?

My react component makes an axios.post to an

3条回答
  •  春和景丽
    2020-12-21 21:40

    You need to find out where in the json object that transactionHash is located.

    To find out the structure log the output first and examine the console.

    console.log(res.data)
    

    If the lets assume its under the data object eg:

    "data: {
    "transactionHash": "0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9"
    }
    

    This is how you would set the state:

    axios.post(
      "http://compute.amazonaws.com:3000/users",
      {
        value: this.props.value,
        fileName: this.props.fileName,
        hash: this.props.hash
      }
    )
    .then(res => {
      console.log(res.data)
      this.setState({ hash: res.data.transactionHash });
    });
    

    Tthe finished state would then be:

    {
    items: {},
    hash: "0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9"
    
    }
    

    You can of course use destructuring but first we need to know the shape of the data that is coming back from the server

提交回复
热议问题