SetState功能未分配布尔值.为什么



我是新手反应天然的,我无法解开这种行为。在异步函数中,我在API调用之前将加载布尔值设置为状态。现在是奇怪的:收到响应后,我无法将加载布尔值设置为false。它只是在setState函数上不断等待而无需到达回调即可。

我已经尝试在每个值的多个调用中设置state。或全部一个功能调用。我还试图将整个响应分配给状态。在React Antial I中,我可以在获取后端时将响应记录在响应中。另外,我可以在将加载布尔值拒之门(接听回调(时将响应分配给状态。但是,当试图将加载布尔值设置为false时,我却不能分配响应。提示(也许(:在JSON响应中,我包括一个数组。当排除数组(不将其分配给状态(时,它的行为应像...请帮忙!

// here my mistery
export default class App extends React.Component {  
 constructor(props) {
  super(props);
 this.state = {
  loading: false,   
}
}
async onLogin() {
try {
  this.setState({ loading: true }, function () {
    console.log('loading is:' + this.state.loading)
  }); //works great
  const { name, password } = this.state;
  //here the api call
  const response = 
 await fetch(`http://10.0.2.2:3000/api/login/${name}&${password}`);
  const answer = await response.json();
  if (answer.user == 'OK') {
    //now the strange function-call
    this.setState({
      tickets: answer.tickets, //this is the array..!
      title: answer.event.title,
      token: answer.token.token,
      tokenDa: true,
      //loading: false, //only reaching callback when commenting that out
    }, function () {
      console.log('tickets are :' + this.state.tickets[0].kategorie)
    })
    // same behaviour here 
    // this.setState({loading: false},  function(){
    //   console.log('loading ist ' + this.state.loading);
    // });
  }
}
catch{
  console.log('in CATCH ERROR')
}
}
// here also the render function in case that matters:
render() {
if (this.state.loading) {
  return (
    <View style={styles.container}>
      <ActivityIndicator size='large' />
    </View>
  );
}
return this.state.tokenDa ? (
  <View style={styles.container}>
    <Text>Event Title : {this.state.title} </Text>

    <Button
      title={'scan'}
      style={styles.input} 
    />
    {this.state.tickets.map((ticket, i) => (
      <div key={i}>
        <Text >TicketKategorie : {ticket.kategorie}</Text>
        <Text > Datum und Türöffnung {ticket.gueltig_am}</Text>
        <Text >Verkauft {ticket.verkauft}</Text>
        <Text >Eingescannt {ticket.abbgebucht}</Text>
      </div>
    ))}
  </View>
) : (
    <View style={styles.container}>
      <TextInput
        value={this.state.name}
        onChangeText={(name) => this.setState({ name })}
        placeholder={'Username'}
        style={styles.input}
      />
      <TextInput
        value={this.state.password}
        onChangeText={(password) => this.setState({ password })}
        placeholder={'Password'}
        secureTextEntry={true}
        style={styles.input}
      />
      <Button
        title={'Login'}
        style={styles.input}
        onPress={this.onLogin.bind(this)}
      />
    </View>
  )
};
};

结果是:由于加载属性,我无法将其设置为False,因此加载屏幕。为什么会发生!?

您需要在第一个setState的回调中包装其余的代码,例如...

this.setState({ loading: true }, async function () {
  const { name, password } = this.state;
  const response = 
 await fetch(`http://10.0.2.2:3000/api/login/${name}&${password}`);
  const answer = response.json();
  if (answer.user == 'OK') {
    this.setState({
      tickets: answer.tickets, //this is the array..!
      title: answer.event.title,
      token: answer.token.token,
      tokenDa: true,
      loading: false
    });
  }
});

您可能已经推论出来的,固定性的异步性质存在问题。为了解决此问题,我们可以创建另一个功能来处理实际的API请求,并在第一个设定状态的呼叫背包中使用它。

setLoading = () => {
    this.setState({ loading: true }, () => this.onLogin())
}
onLogin = async () => {
  const { name, password } = this.state;
  //here the api call
  const response = await fetch(`http://10.0.2.2:3000/api/login/${name}&${password}`);
  const answer = await response.json();
  if (answer.user == 'OK') {
    this.setState({
      tickets: answer.ticketsm
      title: answer.event.title,
      token: answer.token.token,
      tokenDa: true,
      loading: false
    }, function () {
      console.log('tickets are :' + this.state.tickets[0].kategorie)
    })
}

最新更新