【问题标题】:React JS - Missing semicolon after renderReact JS - 渲染后缺少分号
【发布时间】:2021-11-27 02:34:11
【问题描述】:

我正在尝试构建一个基本的 crud 应用程序,但我无法理解为什么我的 crud 应用程序不呈现。我预计这可能是一个非常基本的问题,但我对编码(和 Stack Overflow)一般来说是新手,所以它在逃避我。

import { FormGroup, InputLabel, FormControl, Button, Input, makeStyles, Typography } from "@material-ui/core"
import react, { useState } from "react"
import { addContact } from "../Service/api";
import { useHistory } from "react-router-dom";
import * as React from 'react';
import Box from '@mui/material/Box';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import TextField from '@mui/material/TextField';
import AdapterDateFns from '@mui/lab/AdapterDateFns';
import LocalizationProvider from '@mui/lab/LocalizationProvider';
import DatePicker from '@mui/lab/DatePicker';
import validator from 'validator';
import dayjs from 'dayjs';
import Alert from '@mui/material/Alert';
import { render } from "react-dom";
const useStyle = makeStyles({
    container: {
        width: '50%',
        margin: '5% 0 0 25%',
        '& > *': {
            marginTop: 20
        }
    }

})


const initialValues = {
    name: '',
    email: '',
    phone: '',
    location: ''
}
const AddContact = () => {
    const [contacts, setContact] = useState(initialValues);

    const { name, email, phone, location } = contacts;
    const classes = useStyle();
    const history = useHistory();

    const onValueChange = (e) => {
            setContact({ ...contact, [e.target.name]: e.target.value })
    }
    const [regdates, setValue] = React.useState(new Date());

    let regdate= parseInt(regdates.getMonth()+1) + "/"+ regdates.getDate() +"/"+regdates.getFullYear();
    
    const contact = {...contacts,regdate};
    console.log(contact);
    console.log(regdate);


    const addContactDetails = async () => {
        await addContact(contact);
        history.push('./AllContact');
    }
    const validate = () => {

        // Validation of Info
    
        let isValid = true;
    
        let name = '';
    
        let email = '';
    
        let contact = '';
    
        let location = '';
    
        let regDate = '';
    
    
    
        let nameCheck = this.refs.fullname.value;
    
        let emailCheck = this.refs.email.value;
    
        let contactCheck = this.refs.contact.value;
    
        let locationCheck = this.refs.location.value;
    
        let regDateCheck = this.refs.regdate.value;
        // Validation of full name

    if (nameCheck.length >= 30) {

        name = 'Full Name field accept up to 30 in size only';
  
        isValid = false;
  
        this.refs.fullname.value = '';
  
      }
  
      // Validation of full name to check if it has numbers
  
      if (typeof nameCheck !== 'undefined') {
  
        if (!nameCheck.match(/^[,.a-zA-Z\s]*$/)) {
  
          name = 'Full Name field accept characters values only';
  
          isValid = false;
  
          this.refs.fullname.value = '';
  
        }
  
      }
  
      if (!nameCheck) {
  
        name = 'Full Name field cannot be blank';
  
        isValid = false;
  
        this.refs.fullname.value = '';
  
      }
      // Validation of Email

    if (emailCheck.length >= 45) {

        email = 'Email Address field accept up to 45 in size only';
  
        this.refs.email.value = '';
  
        isValid = false;
  
      } else if (!validator.isEmail(emailCheck)) {
  
        email = 'Email Address field should have email domain';
  
        isValid = false;
  
        this.refs.email.value = '';
  
      }
      if (!emailCheck) {

        email = 'Email Address field cannot be blank';
  
        isValid = false;
  
        this.refs.email.value = '';
  
      }
  
  
  
      // Validation of contact number
  
      if (contactCheck.length !== 11) {
  
        contact = 'Contact Number field accept up to 11 in size only';
  
        this.refs.contact.value = '';
  
        isValid = false;
  
      }
  
      if (typeof contactCheck !== 'undefined') {
  
        if (!contactCheck.match(/^[0-9]*$/)) {
  
          contact = 'Contact Number field accept numeric values only';
  
          isValid = false;
  
          this.refs.contact.value = '';
  
        }
  
      }
  
      if (!contactCheck) {
  
        contact = 'Contact Number field cannot be blank';
  
        isValid = false;
  
        this.refs.contact.value = '';
  
      }
      // Validation of location

    if (!locationCheck) {

        location = 'Location field cannot be blank';
  
        isValid = false;
  
        this.refs.location.value = '';
  
      }
  
  
  
      // Validation of registered date
  
      if (!regDateCheck) {
  
        regDate = 'Registered Date field cannot be blank';
  
        isValid = false;
  
        this.refs.regdate.value = '';
  
      } else if (regDateCheck !== dayjs(new Date()).format('YYYY-MM-DD')) {
  
        regDate = 'Registered date field can only accept current date';
  
        isValid = false;
  
        this.refs.regdate.value = '';
  
      }
      if (!isValid) {

        this.setState({
  
          errors: {
  
            nameError: name,
  
            emailError: email,
  
            contactError: contact,
  
            locationError: location,
  
            regDateError: regDate,
  
          },
  
        });
  
        return false;
  
      }
  
      return true;
  
    };

    
   
render(){
return (
  <FormGroup className={classes.container}>
      <Typography variant="h4">Add Contact</Typography>
      <FormControl>
          <InputLabel>Full Name *</InputLabel>
          <Input onChange={(e) => onValueChange(e)} name='name' value={name} placeholder="Last Name, First Name Middle Initial" ref="fullname" defaultValue="" required />
          {this.state.errors['nameError'] ? (
                <Alert color="danger">
                  <strong>{this.state.errors['nameError']}!</strong>
                </Alert>
              ) : null}
      </FormControl>
      <FormControl>
          <InputLabel>Email Address *</InputLabel>
          <Input onChange={(e) => onValueChange(e)} name='email' value={email} placeholder="example@email.com" ref="email"  required/>
          {this.state.errors['emailError'] ? (
                <Alert color="danger">
                  <strong>{this.state.errors['emailError']}!</strong>
                </Alert>
              ) : null}
      </FormControl>
      <FormControl>
          <InputLabel>Contact Number *</InputLabel>
          <Input onChange={(e) => onValueChange(e)} name='phone' value={phone} placeholder="09XXXXXXXXX" required/>
          {this.state.errors['contactError'] ? (
                <Alert color="danger">
                  <strong>{this.state.errors['contactError']}!</strong>
                </Alert>
              ) : null}
      </FormControl>
      <Box sx={{ minWidth: 120 }}>
      <InputLabel>Location *</InputLabel>

          <FormControl fullWidth>
              <Select
                  required
                  labelId="demo-simple-select-label"
                  id="demo-simple-select"
                  onChange={(e) => onValueChange(e)}
                  value={location}
                  label="location"
                  name="location"
                  ref="location"
              >
                  <MenuItem value="">Select Location</MenuItem>
                  <MenuItem value="Manila">Manila</MenuItem>
                  <MenuItem value="Cebu">Cebu</MenuItem>
              </Select>
              {this.state.errors['locationError'] ? (
                <Alert color="danger">
                  <strong>{this.state.errors['locationError']}!</strong>
                </Alert>
              ) : null}
          </FormControl>
      </Box>
      <FormControl>
          <LocalizationProvider dateAdapter={AdapterDateFns}>
          <DatePicker
    disableFuture
    label="Register Date*"
    views={['year', 'month', 'day']}
    value={regdates}
    name='regdate'
    ref="regdate"
    onChange={(newValue) => {
      setValue(newValue);
    }}
    renderInput={(params) => <TextField {...params} />}
  />
  
</LocalizationProvider>
{this.state.errors['regDateError'] ? (
                <Alert color="danger">
                  <strong>{this.state.errors['regDateError']}!</strong>
                </Alert>
              ) : null}
      </FormControl>
      <Button variant="contained" onClick={() => addContactDetails()} color="primary">Add Contact</Button>
  </FormGroup>
)
}
}
export default AddContact

这应该会显示一个可用聊天室的列表和一个用于添加更多的输入字段,但错误消息如下:

    Failed to compile.
[0]
[0] ./src/Components/AddContact.jsx
[0] SyntaxError: C:\ReactJS\CRUD\crud-app\src\Components\AddContact.jsx: Missing semicolon (254:8)
[0]
[0]   252 |
[0]   253 |
[0] > 254 | render(){
[0]       |         ^
[0]   255 | return (
[0]   256 |   <FormGroup className={classes.container}>
[0]   257 |       <Typography variant="h4">Add Contact</Typography>

【问题讨论】:

  • 你应该知道类组件和功能组件的区别。请阅读本文档reactjs.org/docs/components-and-props.html
  • render 只需要当你在类组件中。
  • 非常感谢,我现在明白我的问题所在了。
  • 太好了???

标签: javascript reactjs react-native jsx


【解决方案1】:

你混淆了两种不同的结构。

在你的情况下,你可以删除渲染:

 render(){

}

只留下

return (
//your code
);

我找到了这篇文章,它解释了结构之间的主要区别。 https://samarthnehe.medium.com/react-hooks-vs-class-components-c344b59f3bc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    • 2021-12-29
    • 2020-03-22
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多