反应原生警报

Alert in react native

我在状态 true/false 中设置错误,如果错误 = true 则想要显示警报
所以我这样做了。

constructor() {
    super()
    this.state = {
        email: "",
        password: "",
        error: false
    }
    this.handleSignUp = this.handleSignUp.bind(this)
}

和函数

handleSignUp() {
    fetch('http://myIp:9999/signUp', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(this.state),
    })
        .then((res) => {
            console.log("here")
            console.log(res)
            this.setState({error: false})
        }).catch((e) => {
        if (e) {
            console.log('e')
            console.log(e.status)
            this.setState({error: true})
        }
    })

}

和渲染方法为

 render() {

    var alert1 = alert(
        "User exist",
        "User with same Email exist. Try some to login or use other Email",
        [
            {text: "Ok", style: 'cancle', onPress: () => this.setState({error: false})}
        ]
    )


    return (
        <View style={styles.container}>
            {this.state.error ? alert1 : ""}
            <Header function1={() => this.props.navigation.openDrawer()}/>
            ....
        </View>
    )
}

结果是无论错误是真还是假,当我打开这个屏幕时都会出现警报,然后出现错误

所以我更改了 alert1。

var alert1 =    (<View> 
                                    alert(
                                            "User exist",
                                            "User with same Email exist. Try some to login or use other Email",
                                            [
                                                {text:"Ok",style:'cancle',onPress:()=> this.setState({error:false})}
                                            ]
                                        )
                                    </View>)

现在错误已解决,但屏幕上出现加载警报。

handleSignUp() {
    fetch('http://myIp:9999/signUp', {
        ...
    })
      .then((res) => {
          //insted of this line => this.setState({error: false}) call Alert directly

            Alert.alert(
              'Alert Title',
              'My Alert Msg',
              [
                {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
                {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
                {text: 'OK', onPress: () => console.log('OK Pressed')},
              ],
              { cancelable: false }
            )
      })

}