微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ReactJS:未捕获的ReferenceError:[变量]未定义

如何解决ReactJS:未捕获的ReferenceError:[变量]未定义

我是Reactjs的新手,但我有一个未定义变量的问题。在控制台日志中,我从以下React页面获取“ Uncaught ReferenceError:未定义drawResults app.js:116002”:

 import React,{ Component } from "react";
    import ReactDOM from "react-dom";
    import { render } from 'react-dom';
    import '@fortawesome/fontawesome-free/css/all.min.css';
    import "bootstrap-css-only/css/bootstrap.min.css";
    import "mdbreact/dist/css/mdb.css";
    import { NumberPicker } from 'react-widgets';
    import NumberPicker from 'react-widgets/lib/NumberPicker'
    import PropTypes from "prop-types";
    import Radium,{Style} from 'radium';
    import { MDBBtn,MDBInput,MDBModal,MDBModalBody,MDBModalHeader,MDBModalFooter,MDBIcon,MDBBadge,MDBContainer,MDbrow,MDBCol,MDBSelect,MDBInputNumeric} from "mdbreact";
    import { event } from "jquery";
    import axios from 'axios';


class App extends Component {  

    static propTypes = {
        kind: PropTypes.oneOf(['input','button'])
    };

    constructor(props) {
        super(props);
        this.state = {

              drawResults: [],mainDrawSet: 40,mainBallsDrawn: 5,powerBallSet: 5,powerballBallsDrawn: 0
          
        };
       
    }

    componentDidMount(){
        this.fetchResults();
   }
  
    playLotto (mainDrawSet,mainBallsDrawn,powerBallSet,powerballBallsDrawn) {  
        
        fetch('/draw',{                
                method: 'post',body: JSON.stringify({draw:this.state}),headers: {
                    'Access-Control-Allow-Origin':'*','Content-Type':'x-www-form-urlencoded','Accept': 'application/json','Content-Type': 'application/json;charset=UTF-8',}
            })
        .then(res => {
            console.log(res)
        })
        .catch(err => {
            console.log(err)
        })
        console.log(this.state);

        
    };

    submit () {
                this.playLotto(this.state.mainDrawSet,this.state.mainBallsDrawn,this.state.powerBallSet,this.state.powerballBallsDrawn)
        

        this.setState({
          
              mainDrawSet: 40,powerballBallsDrawn: 0
        })
    };

    exportTasks = (_this) => {
        let _url = $(_this).data('href');
        window.location.href = _url;
     }

    fetchResults = async () => {


        try {
            const res = await fetch('/lotto_results',{
                method: 'GET',headers: {
                    'Accept': 'application/json','Content-Type': 'application/json'
                }
            });
            const res_1 = await res.json();
            return this.setState({ drawResults: res_1.data });
        } catch (err) {
            return console.log(err);
        }
    } 

    render() {
    
        return (        
            <MDBContainer>
                <MDbrow>
                    <MDBCol md="12" className="mb-r">
                        <h2 className="text-uppercase my-3">Lotto Draw Machine:</h2>
                        <div data-test="container" className="container-fluid section mb-5 border p-3">                            
                                                
                            <form className="mx-3 grey-text row" style={{ position: "relative",marginTop: "1.5rem",marginBottom:"1.5rem"}} data-test="row"> 
                                <div className="form-row align-items-center">
                                    <div data-test="col" className="col">
                                        <div className="md-form form-group form-lg md-bg" style={{position: "relative",marginBottom: "1.5rem"}}> 
                                            <label style={{ position: "relative",marginBottom:"1rem"}} htmlFor="mainDrawSet">Number of balls in main draw set</label>
                                            <NumberPicker min={40} max={49} defaultValue={40} type="number" className="custom-select" id="mainDrawSet" value={this.state.mainDrawSet} onChange={mainDrawSet => this.setState({ mainDrawSet})} style={{width: "400px",height: "40px"}}/>                            
                                            <label style={{ position: "relative",marginBottom:"1rem"}} htmlFor="mainDrawSet">Please choose a number between 40 and 49</label>
                                        </div>
                                    </div>
                                    <div data-test="col" className="col">
                                        <div className="md-form form-group form-lg md-bg">
                                            <label style={{ position: "relative",marginBottom:"1rem"}} htmlFor="mainDraw">Number of balls in main draw</label>
                                            <NumberPicker min={5} max={7} defaultValue={5} type="number" className="custom-select" id="mainDraw" value={this.state.mainBallsDrawn} onChange={mainBallsDrawn => this.setState({ mainBallsDrawn })} style={{width: "400px",height: "40px"}}/>
                                            <label style={{ position: "relative",marginBottom:"1rem"}} htmlFor="mainDraw">Please choose a number between 5 and 7</label>      
                                        </div>                            
                                    </div>       
                                </div>                       
                                 
                                <div className="mx-3 grey-text row" style={{ position: "relative",marginBottom:"1.5rem"}} data-test="row"> 
                                    <div className="form-row align-items-center">
                                        <div data-test="col" className="col">
                                            <div className="md-form form-group form-lg md-bg" style={{position: "relative",marginBottom: "1.5rem"}}>
                                                <label htmlFor="powerBallSet" style={{ position: "relative",marginTop: "0.5rem",marginBottom:"0.5rem"}}>Powerball Set</label>
                                                <NumberPicker min={5} max={49} defaultValue={5} type="number" className="custom-select" id="powerBallSet" value={this.state.powerBallSet} onChange={powerBallSet => this.setState({ powerBallSet })} style={{width: "400px",height: "40px"}}/>  
                                                <label htmlFor="powerBallSet" style={{ position: "relative",marginBottom:"0.5rem"}}>Please choose a number between 5 and 49</label>
                                            </div>                            
                                        </div>
                                        <div data-test="col" className="col">
                                            <div className="md-form form-group form-lg md-bg">
                                                <label htmlFor="powerBall" style={{ position: "relative",marginBottom:"0.5rem"}}>Number of powerball balls</label>
                                                <NumberPicker min={0} max={3} defaultValue={0} type="number" className="custom-select" value={this.state.powerballBallsDrawn} onChange={powerballBallsDrawn => this.setState({ powerballBallsDrawn})} id="powerBall" style={{width: "400px",height: "40px"}}/>  
                                                <label htmlFor="powerBall" style={{ position: "relative",marginBottom:"0.5rem"}}>Please choose a number between 0 and 3</label>     
                                            </div>                            
                                        </div>                              
                                    </div>                       
                                </div>
                                <div className="mx-3 grey-text row" style={{ position: "relative",marginBottom:"1.5rem"}} data-test="row">                          
                                    <div data-test="row" className="row">
                                        <button data-test="button" type="button" className="btn-info btn Ripple-parent" style={{width: "400px",height: "40px"}} onClick={()=>{this.submit()}}>Let's Play!<div data-test="waves" className="Ripple "></div></button>
                                    </div>  
                                </div>                                     
                            </form>                        
                        </div>                        
                    </MDBCol>                    
                </MDbrow>
                <MDbrow>
                    <MDBCol md="7" className="mb-r">
                                <div className="mx-3 grey-text row" style={{ position: "relative",marginBottom: "1.5rem"}}>
                                             <h4 className="text-uppercase my-3">Lotto Results:</h4>                                                   
                                            </div>                            
                                        </div>
                                        <div data-test="col" className="col">
                                            <div className="md-form form-group form-lg md-bg">                        
                                              <button data-href="/tasks" data-test="button" type="button" className="btn-info btn mr-5 Ripple-parent" style={{width: "400px",height: "40px"}} onClick={()=>{this.exportTasks(event.target)}}>Export To CSV</button>
                                            </div>                           
                                        </div>                              
                                    </div>   
                                </div>                                 
                    </MDBCol>                               
                </MDbrow>

                <MDbrow>                
                    
                    <MDBCol md="12" className="mb-r">
                    return {drawResults.map((result,index) => 
                        <div key={index} className="mx-3 grey-text row" style={{ position: "relative",marginBottom:"1.5rem"}} data-test="row"> 
                            <table className="table center">
                                <thead className="grey lighten-2">
                                    <tr>
                                        <th scope="col">Draw Time</th>
                                        <th scope="col"> Draw Result</th>
                                        <th scope="col"> Number of Main Balls Drawn</th>
                                        <th scope="col">Number of Powerball Balls Drawn</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                    <th scope="row">result.draw_time</th>
                                        <td>result.results</td>
                                        <td>result.main_draw_balls</td>
                                        <td>result.power_balls</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>    
                        )}       
                    </MDBCol>         
                </MDbrow>
            
            </MDBContainer>            
        
        );
    }               

     }
        App = Radium(App);

       export default App;

      if (document.getElementById('app')) {
      ReactDOM.render(
        <App />,document.getElementById('app'));
     }

可能有人建议如何解决错误。我已经在构造函数中声明了状态变量,并尝试在fetchResults()方法中为其分配值,但是脚本失败,变量未定义。

解决方法

我认为您的问题来自 return this.setState({ drawResults: res_1.data });

由于setState只是修改了组件的状态,因此您无法返回setState,您应该尝试使用this.setState({ drawResults: res_1.data });

,

该脚本失败,并显示“未定义”错误,因为该变量确实未定义。

您说您已经在构造函数中声明了它。您实际上在构造函数中执行的操作是创建this.state的属性(或更准确地说,创建您随后分配给this.state的对象的属性)。很好,但是您需要引用属性,而不是变量。

要解决该错误,请将drawResults更改为this.state.drawResults

编辑:我打算更改此行:return {drawResults.map(...

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。