【问题标题】:Use if in the state component in react-native在 react-native 的状态组件中使用 if
【发布时间】:2021-10-06 12:21:54
【问题描述】:

所以我创建了一个个人资料图片,但是用户在反应导航中,当我想和我的用户一起输入时它给出了一个错误,这里是代码:

export default class Profile extends Component{
  state = {
    errorMessage: null,
    project:[],
    user:{
     id:  this.props.route.params.name  //here is where it gives the error i want to find a way to make something like if (undefined) async storage ....
    }
  }
    
  getUser = async() => {
      try{
        console.log('1')
        const usu =  await AsyncStorage.getItem('@backend:user')
        console.log('2')
        userID = this.state.user.id
        console.log('3')
        console.log(userID)
        const response = await api.get(`/auth/` + userID)
        console.log('4')
        console.log(response.data)
   
        const { project } = response.data
        console.log('5')
        this.setState({ project })
       }catch (response){
         this.setState({ errorMessage: response.data.error})
     }
    
    
 }

【问题讨论】:

  • ??????????????????????

标签: android react-native profile


【解决方案1】:

您可以将其设置为 undefined,然后在 componentDidMount 中执行一些 setState。

但您也可以在 react native 中使用 三元运算符

id: this.props.route.params.name ? this.props.route.params.name : undefined

此代码检查参数是否存在并接受它,如果它不存在,则将状态设置为未定义。

您还可以进行一些额外的检查,例如:

id: this.props.route.params.name == "myname" ? this.props.route.params.name : undefined

在这种情况下,如果名称为 myname,则将其设置为,否则将其设置为 undefined

更多信息:https://reactjs.org/docs/conditional-rendering.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-12
    • 1970-01-01
    • 2018-09-25
    • 2020-05-14
    • 1970-01-01
    • 2022-07-06
    相关资源
    最近更新 更多