简体   繁体   中英

How can I initialize state inside a React Component for an integer data type?

I'm trying to initialize state inside one of my React Components for an integer data type. Right now my state looks like this:

state = {
  username: '',
  email: '',
  password: '',
  user_id: null,
  id: null,
  toy_id: null,
  loading: false,
}

Because they are not strings I have been using null for user_id , id and toy_id , however later down the road when I pass down the properties:

const { email, password, user_id, id, toy_id } = this.state

// ...

await this.props.loginUserToy(email, password, id, toy_id)

console.log('LOGIN loginUserToy email', email)
console.log('LOGIN loginUserToy password', password)
console.log('LOGIN loginUserToy id', id)
console.log('LOGIN loginUserToy toy_id', toy_id)

Here is loginUserToy from my action creators page:

export const loginUserToy = async (email, password, id, toy_id) => {
  try {
    const response = await axios({
      method: 'POST',
      url: `${API_URL}/api/get_token`,
      data: {
        email,
        password
      }
    })

    const { token } = response.data

    const userResponse = await axios({
      method: 'POST',
      url: `${API_URL}/api/login`,
      headers: {
        Authorization: `${token}`
      },
      data: {
        email,
        password
      }
    })

    const getProfileResponse = await axios({
      method: 'POST',
      //url: `${API_URL}/api/user_profile`,
      url: `${API_URL}/api/toy`,
      headers: {
        Authorization: `${token}`
      },
      data: {
        id,
        toy_id
      }
    })

    const { Name, Description, Where, When, Picture } = getProfileResponse.data

    return {
      type: FETCH_TOY,
      payload: {
        token,
        email,
        password,
        id,
        toy_id,
        name: Name,
        description: Description,
        location: Where,
        date: When,
        image: Picture
      }
    }
  }
  catch (err) {
    console.log('Exception in actions/user/loginUser err', err)
  }
}

I get back 't' & 't' for the first two logs (which is correct) but I continue to get back null for the second two logs. I understand an empty string is different from a null which means a non-existent value.

However, is there something else I can do here?

Try simply initializing them as 0 instead of as null .

state = {
  username: '',
  email: '',
  password: '',
  user_id: 0
  id: 0,
  toy_id: 0,
  loading: false,
}

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