在 React Native 中调用或分配变量值时遇到问题 Class

Trouble calling or assigning variable value in React Native Class

我在 React Native 中有以下 class。可以看出,我有一些已定义的 'state' 变量和一个 'componentDidMount' 调用,旨在使用 'AsyncStorage' 工具检索以前存储的变量。

export default class Cast extends Component {
state = {
  admin: false,
  isPublishing: false,
  userComment: "",
  hasPermission: false,
  paused: true,
  _email: false,
  _name: false,
  _pword: false,
};


getKey = async() => {
  try {
    var value = await AsyncStorage.getItem('email');
console.log("value variable AFTER getKey: " + value);
    this.setState({ _email: value });
  } catch (error) {
    console.log("Error retrieving data" + error);
  }
}

componentDidMount(){
  this.getKey();
}

onPressBtn = () => {
console.log("EMAIL value variable AFTER getKey: " + this.state._email)  //this should show the value AFTER the retrieval from storage...correct?
};

//...

'AsyncStorage.getItem' 之后的 console.log 语句成功显示从存储中检索到的变量“value”(示例“me@gmail.com”)。但是我对如何分配和显示这个变量感到非常困惑。 “this.setState({ _email: value });”要么不起作用,要么我使用不正确的语法来显示“_email”变量的值。我尝试了以下操作:

console.log("_email variable AFTER getKey: " + _email);
console.log("_email variable AFTER getKey: " + this._email);
console.log("_email variable AFTER getKey: " + {_email});
console.log("_email variable AFTER getKey: " + this.state._email);

None 以上正确 return "_email" 变量的值。我在这里做错了什么? 'setState' 赋值不正确...?我只是想检索存储中的任何值(作为“值”),然后将它们分配给 'state' 中定义的适当变量。非常感谢任何建议。我先谢谢你了。

这取决于 when 您是否尝试访问状态变量。如果您执行了以下操作:

getKey = async() => {
  try {
    var value = await AsyncStorage.getItem('email');
    console.log("value variable AFTER getKey: " + value);
    this.setState({ _email: value });
    console.log(this.state._email)
  } catch (error) {
    console.log("Error retrieving data" + error);
  }
}

然后,这将打印 false,这是您所在州的默认设置。设置状态将导致重新渲染。新值将在之后可用。

考虑以下片段。

getKey = async () => {
    try {
      var value = "test"
      console.log("value variable AFTER getKey: " + value)
      this.setState({ _email: value })
    } catch (error) {
      console.log("Error retrieving data" + error)
    }
  }

 ...

  render() {
    console.log("HELLO VALUE", this.state._email)
    return <></>
  }

我们会注意到以下输出打印到控制台。

LOG  HELLO VALUE false
LOG  value variable AFTER getKey: test
LOG  HELLO VALUE test

您需要在构造函数中声明状态对象

constructor(props) {
  super(props);
  
  this.state = { 
  admin: false,
  isPublishing: false,
  userComment: "",
  hasPermission: false,
  paused: true,
  _email: false,
  _name: false,
  _pword: false,
};
  
//Other codes

}

另外,当提到一个状态时,你想使用: 例如。您正在尝试获取存储在 state

中的电子邮件
this.state._email

//setting states
this.setState({_email: "newEmail"})