简体   繁体   中英

React Native how to setState data inside data?

For example:

We have in the constructor the avatar data, inside the avatar there is thumb and inside the thumb the url. I just want to get the url. anyone has any hint to spare?

{avatar: {:thumb{:url}}}


   constructor(props) {
        super(props);

        this.state = {
            id: "",
            avatar: "",
            bio: "",
            error: "",
        }
    }

在此处输入图片说明

fetched user data

  async fetchUserId()  {

         let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);



  fetch("https://xxx.herokuapp.com/api/users/"+auth_token+"", {
  method: 'GET',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },

}).then((response) => response.json())
   .then((json) => {


    this.state.id = json.id

//this.state.url =  json.avatar.thumb.url



  })
    .catch((error) => {
      console.error(error);
    });

}

Update:

you're not setting json.id and json.avatar correctly to the state you need to use setState

this.setState({ id: json.id,avatar: json.avatar })

Solution one

 constructor(props) {
        super(props);

        this.state = {
            id: "",
            avatar: {},
            bio: "",
            error: "",
            url: ""
        }

    }

getUrl = () =>{
if(this.state.avatar && this.state.avatar.thumb && this.state.avatar.thumb.url){
      this.setState({ url: this.state.avatar.thumb.url })
   } 
}

<button onClick={this.getUrl}>Get URL </button>

Solution Two

Because avatar is coming from async I suggest you to use componentWillUpdate lifecycle method

componentWillUpdate(nextProps, nextState){
   if(this.state.avatar !== nextState.avatar){
     console.log(nextState.avatar.thumb.url)
   }
}

Note: componentWillUpdate will invoket on everytime that this.state.avatar changes

Since you cannot mutate the state, and since setState doesn't handle nested updates, you need to use the following code to set such a state:

this.setState(prevState => ({
    ...prevState,
    avatar: {
        ...prevState.avatar,
        thumb: {
           ...prevState.avatar.thumb,
           url: newUrlValue
        }
    }
}))

Like This You can set:-

class App extends Component {
  state = {
    name: "",
    stars: "",
    icon: "",
      longitude: "",
    address:"",
     latitude: "",
    trails: [], isLoaded: false
  }




  handleChange = address => {
   this.setState({
      address

    });

        geocodeByAddress(address)
            .then(res => getLatLng(res[0]))
      .then(({ lat, lng }) => {
    this.setState({

      latitude: lat,
      longitude: lng,

    });
  })
 .catch(error => {
        this.setState({ isGeocoding: false });
        console.log('error', error); // eslint-disable-line no-console
      });

 }

  getUser = selected => {

var object = this.refs.Progress2;

object.innerHTML="";


 this.setState({ isGeocoding: true, address: selected });

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