При выполнении запроса Post свойство и значение становятся равными нулю - PullRequest
0 голосов
/ 27 января 2020

Я делал запрос на регистрацию с некоторыми текстовыми полями, но после нажатия кнопки отправки параметры и значения становятся пустыми. Я установил имена во всех текстовых полях, но все еще остается пустым, также добавил необходимый метод, заголовок и тело, но мне нужна помощь. В качестве ссылки прилагаю код, заранее спасибо

export class RegisterPage extends Component{

    constructor(props){
        super(props)
        this.state={
            userName : '',
            userEmail : '',
            mobileNumber : '',
            userPassword : ''
        } 
    }

    userRegister = () => {
        const {userName, userEmail, mobileNumber, userPassword} = this.state;

        fetch('http://localhost/jkdapi/index.php/AndroidApi/test', {
            method: 'POST',
            header:{
                'Accept': 'application/json',
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                your_name : userName,
                email: userEmail,
                phone: mobileNumber,
                password: userPassword,
            })
        })
        .then((response) => response.text())
            .then((responseJson)=>{
                alert(responseJson);
            })
            .catch((error)=>{
                console.error(error);
            });
    }

    render(){
        return(
            <View style ={{width: '100%', height: "100%", justifyContent: 'center', 
             alignContent: 'center', alignSelf: 'center', backgroundColor : 'white'}}>
                <Icon name="chevron-left" color="grey" onPress={() => this.props.navigation.goBack()} size={25} style={{ position: 'absolute', top: 30, left: 10 }} />
                <Text style ={styles.headingtext}>Hello there!</Text>
                <Text style ={{marginLeft: 45}}>Enter details for Sign Up.</Text>
                <TextInput 
                    placeholder = {"Enter the username"}
                    onChangeText={userName => this.setState({userName})}
                    style={styles.textinput1} />
                <TextInput 
                    placeholder = {"Enter the email"}
                    onChangeText={userEmail => this.setState({userEmail})}
                    style={styles.textinputrest} />
                <View style={{flexDirection: "row", marginHorizontal: 42, paddingHorizontal: 10, height: 50, 
                    width: '80%', borderRadius: 1, borderColor: 'orange', borderWidth: 1,
                    marginTop: '5%'}}>
                    <Image style={{height: 150, width: 30, marginTop: '5%', resizeMode: 'contain', alignSelf: 'center', justifyContent: 'center'}} source = {require('../../image/ic_australia.png')}/>
                    <Text style={{alignSelf: 'center', justifyContent: 'center', marginTop:"5%", marginLeft: 10, borderRightWidth:1, paddingRight: 10, borderRightColor: 'orange'}}>+61</Text>
                    <TextInput 
                        placeholder = {"Enter the Phone number"}
                        onChangeText={mobileNumber => this.setState({mobileNumber})}
                        style={styles.textinputrest1} />
                </View>
                <TextInput 
                        placeholder = {"Enter the password"}
                        onChangeText={userPassword => this.setState({userPassword})}
                        style={styles.textinputrest} />
                <View style={{marginTop:"5%", width: "100%", alignSelf: 'center'}}>
                    <TouchableOpacity onPress = {this.userRegister} 
                        style={styles.button}>
                        <Text style ={{color : 'white', fontWeight: 'bold'}}>CONTINUE</Text>
                    </TouchableOpacity>
                </View>
                <Text style={{justifyContent: 'center', alignSelf: 'center', marginTop:"5%", 
                    color: 'grey', textAlign: 'center'}}>Will send you a OTP to your mobile number {"\n"} for verification</Text>
            </View>
        )
    }
}

1 Ответ

0 голосов
/ 27 января 2020
this.state={
    userName : '',
    userEmail : '',
    mobileNumber : '',
    userPassword : ''
}

должны быть обычными членами класса:

    this.userName : '',
    this.userEmail : '',
    this.mobileNumber : '',
    this.userPassword : ''

Изменение состояния вызывает повторный рендеринг пользовательского интерфейса, и оно сбрасывает ваше состояние до пустых строк. Вы можете изменить его на:

onChangeText={text => this.userEmail = text}

Нет необходимости обновлять состояние.

...