【问题标题】:React Native - unable to use componentWillMount() - syntax errorReact Native - 无法使用 componentWillMount() - 语法错误
【发布时间】:2025-12-12 08:35:01
【问题描述】:

我正在尝试使用 componentWillMount(),但出现语法错误。

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

componentWillMount(){

}

我明白了.... '[projet 目录]/Login.js 中的语法错误:[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',
  },
});

【问题讨论】:

  • 粘贴更多代码,然后我们更容易提供帮助。众所周知(就像我们一样),这两行代码没有任何问题。
  • 这是令人惊讶的事情。我什至不能在没有收到错误的情况下输入这两行代码。我将发布完整的代码。谢谢
  • 据我所见,componentWillMount 似乎不在导出范围内(你在构造函数中用 1 个括号关闭)

标签: javascript react-native


【解决方案1】:

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

【讨论】:

    最近更新 更多