React Native - 无法使用componentWillMount() - 语法错误

时间:2018-01-03 00:13:31

标签: javascript react-native

我试图使用componentWillMount()但是我遇到语法错误。

我删除了里面的所有代码,但仍然有错误。所以我甚至不能写......

componentWillMount(){

}

我得到.... ' [projet目录] /Login.js中的SyntaxError:[projet目录] /Login.js:意外的令牌,预期; (75:20)'

(75:20)对应于括号内(即componentWillMount(此处

//////////////////////// 这是完整的代码:

import React from 'react';
import { StyleSheet, Text, View,Navigator,TextInput, KeyboardAvoidingView,TouchableOpacity,
AsyncStorage,
 } from 'react-native';

import Banana from './Banana';

//var mongoose = require('mongoose');    I cant use mongoose because the front end doesn't have Node.js
import api from './utilities/server_connect'




import {
  StackNavigator,
} from 'react-navigation';



export default class Login extends React.Component {


    //check to see if user has logged in already
    componentDidMount(){
        this._loadInitialState().done();
    }

    //get info from async storage
    _loadInitialState = async () => {
        var value = await  AsyncStorage.getItem('user');

        if(value != null){   //if the user is already logged in
            this.props.navigation.navigate('Profile');      //**profile page that we will create later
        }
    }

    constructor(props){
        super(props);
        this.state = {
            username: '',
            password: '',
            list: [],  //starting with empty array so its allocated before the fetch method works
        }
    }

    //cwm is a lifecycle method
    //its a method that fires right before render happens
}


componentWillMount(){
    api.getData().then((res) => {
        this.setState({
            list: res.data,

        })
    });
}
  render() {

    return (
      //<View style={styles.container}>

        <KeyboardAvoidingView behavior = 'padding' style = {styles.wrapper}>
            <View style = {styles.container}>
                <Text style={styles.header}> - LOGIN - {this.state.data} </Text>
                <TextInput
                    style={styles.textInput} placeholder='Username'
                    onChangeText={(username) => this.setState({username})}
                />
                <TextInput
                    style={styles.textInput} placeholder='Password'
                    onChangeText={(password) => this.setState({password})}
                />
            </View>


            <TouchableOpacity
                style={styles.btn}
                onPress = {this.login}>
                <Text>Log in</Text>
            </TouchableOpacity>

        </KeyboardAvoidingView>


     // </View>
    );
  }

  login = () => {
      alert('test');

      //send to server
      fetch('http://1.1.1.1/3000/users', {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
          },
          body: JSON.stringify({
              username: this.state.username,
              password: this.state.password,
          })
      })

      //handle response
      .then((response) => response.json())
      .then((res) => {

            //if user and pass exists, then log them in
            // res: result
            if(res.sucess === true){
                AysncStorage.setItem('user',res.user);
                this.props.navigation.navigate('Profile'); //navigate user to profile page
            }
            //else, tell the user they dont exist in the database
            else{
                alert(res.message);
            }
      })
      .done();
  }

}


const styles = StyleSheet.create({

    wrapper: {
      flex: 1,
    },

  container: {
    flex: 1,
    backgroundColor: '#2896d3',
    alignItems: 'center',
    justifyContent: 'center',
    paddingLeft: 40,
    paddingRight: 40,
  },

  header: {
    fontSize: 24,
    marginBottom: 60,
    color: '#fff',
    justifyContent: 'center',
    paddingLeft: 40,
    paddingRight: 40,
  },

  textInput: {
    alignSelf: 'stretch',
    paddingLeft: 16,
    marginBottom: 20,
    backgroundColor: '#fff',
  },

  btn: {
      alignSelf: 'stretch',
      padding: 20,
      marginBottom: 20,
      backgroundColor: '#01c853',
      alignItems: 'center',
  },
});

////////////////////

这是componentWillMount()中没有任何内容的代码。两个版本都会出现同样的错误。

import React from 'react';
import { StyleSheet, Text, View,Navigator,TextInput, KeyboardAvoidingView,TouchableOpacity,
AsyncStorage,
 } from 'react-native';

import Banana from './Banana';

//var mongoose = require('mongoose');    I cant use mongoose because the front end doesn't have Node.js
import api from './utilities/server_connect'




import {
  StackNavigator,
} from 'react-navigation';



export default class Login extends React.Component {


    //check to see if user has logged in already
    componentDidMount(){
        this._loadInitialState().done();
    }

    //get info from async storage
    _loadInitialState = async () => {
        var value = await  AsyncStorage.getItem('user');

        if(value != null){   //if the user is already logged in
            this.props.navigation.navigate('Profile');      //**profile page that we will create later
        }
    }

    constructor(props){
        super(props);
        this.state = {
            username: '',
            password: '',
            list: [],  //starting with empty array so its allocated before the fetch method works
        }
    }

    //cwm is a lifecycle method
    //its a method that fires right before render happens
}


componentWillMount(){

}
  render() {

    return (
      //<View style={styles.container}>

        <KeyboardAvoidingView behavior = 'padding' style = {styles.wrapper}>
            <View style = {styles.container}>
                <Text style={styles.header}> - LOGIN - {this.state.data} </Text>
                <TextInput
                    style={styles.textInput} placeholder='Username'
                    onChangeText={(username) => this.setState({username})}
                />
                <TextInput
                    style={styles.textInput} placeholder='Password'
                    onChangeText={(password) => this.setState({password})}
                />
            </View>


            <TouchableOpacity
                style={styles.btn}
                onPress = {this.login}>
                <Text>Log in</Text>
            </TouchableOpacity>

        </KeyboardAvoidingView>


     // </View>
    );
  }

  login = () => {
      alert('test');

      //send to server
      fetch('http://1.1.1.1/3000/users', {
          method: 'POST',
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
          },
          body: JSON.stringify({
              username: this.state.username,
              password: this.state.password,
          })
      })

      //handle response
      .then((response) => response.json())
      .then((res) => {

            //if user and pass exists, then log them in
            // res: result
            if(res.sucess === true){
                AysncStorage.setItem('user',res.user);
                this.props.navigation.navigate('Profile'); //navigate user to profile page
            }
            //else, tell the user they dont exist in the database
            else{
                alert(res.message);
            }
      })
      .done();
  }

}


const styles = StyleSheet.create({

    wrapper: {
      flex: 1,
    },

  container: {
    flex: 1,
    backgroundColor: '#2896d3',
    alignItems: 'center',
    justifyContent: 'center',
    paddingLeft: 40,
    paddingRight: 40,
  },

  header: {
    fontSize: 24,
    marginBottom: 60,
    color: '#fff',
    justifyContent: 'center',
    paddingLeft: 40,
    paddingRight: 40,
  },

  textInput: {
    alignSelf: 'stretch',
    paddingLeft: 16,
    marginBottom: 20,
    backgroundColor: '#fff',
  },

  btn: {
      alignSelf: 'stretch',
      padding: 20,
      marginBottom: 20,
      backgroundColor: '#01c853',
      alignItems: 'center',
  },
});

1 个答案:

答案 0 :(得分:0)

componentWillMount方法之前你有一个额外的右括号。