簡體   English   中英

未捕獲的引用錯誤:未定義狀態(React.js)

[英]Uncaught Reference Error: state is not defined (React.js)

初學者在這里。 這個錯誤不斷彈出,我不知道為什么。 我的網頁確實顯示了我對腳本所做的更改,但只有當我注釋掉樣式以隱藏形狀或保留它以顯示形狀時。

我想創建一個網頁,每秒都會通過其大小、邊框半徑('perCent')和背景顏色來改變形狀的外觀。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> 

    <style>
        .shape-item{
            padding: 10px;
            margin: 20px;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue; 
            border-radius: 50%;  
        }   
    </style>
</head>
<body>
    <div class="shape-item">
        <div></div>
        <div></div>
    </div>

    <script type="text/babel">

        "use strict";

        var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];
        
        class Shapes extends React.Component{

            constructor(props){
                super(props);
                this.state = {
                    shape: {
                        bgColour: colours[Math.floor((Math.random() * colours.length))],
                        size: 100,
                        perCent: "%50"
                    }
                }
            }

            componentDidMount(){
                this.timerID = setInterval(() => this.updateShape(), 1000);
            }

            componentWillUnmount(){
                clearInterval(this.timerID);
            }

            updateShape(){
                let randomIndex = Math.floor((Math.random() * colours.length));
                this.setState(
                    {
                        shape: {
                            bgColour: colours[Math.floor((Math.random() * colours.length))],
                            size: (Math.random() * 125),
                            perCent: (Math.random() * 100)
                        }
                    }
                )
            }

            render(){
                var shapeStyle = {
                    padding: 10,
                    margin: 20,
                    display: 'inline-block',
                    backgroundColor: {this:state.bgColour},
                    borderRadius: {this:state.perCent},
                    width: {this:state.size},
                    height: {this:state.size}
                }
                return(
                    <div style={shapeStyle}>
                        {this.state.shape}
                    </div>
                )
            }
        }

        ReactDOM.render(<Shapes />, document.querySelector(".shape-item"));

        shapesRender = [];

        for(let i=0; i < 60; i++){
            shapesRender.push(<Shapes key={i} />);
        }

        ReactDOM.render(shapesRender, document.querySelector(".shape-item"));

    </script>
</body>
</html>

您正在使用冒號來訪問thisstate屬性。 它應該是一個點。 而且由於您正在構造一個常規 JS 對象以用於內聯樣式,因此您不需要將每個鍵的值放入嵌套的 JS 對象中,就像您為 backgroundColor、borderRadius、寬度和高度所做的那樣。 它應該如下所示:

var shapeStyle = {
  padding: 10,
  margin: 20,
  display: 'inline-block',
  backgroundColor: this.state.bgColour,
  borderRadius: `${this.state.perCent}%`, // append % to numerical perCent value
  width: this.state.size,
  height: this.state.size
}

附加說明,您為perCent提供的初始值是“%50”,它是一個字符串,有一個百分比符號,並且在前面,但每次更新,它都會更改為一個新的 Number 值。 我會從一開始就將其保留為數字(將初始值從perCent: "%50"更改為perCent: 50 )並在最后一步中添加百分號,將其全部插入到樣式對象中,就像我一樣以上。

對於尼克的觀點(在帖子的評論中),如果您想在 div 中顯示狀態對象,以便查看樣式是如何受到影響的,那很好,但您需要使用JSON.stringify(this.state.shape)狀態. JSON.stringify(this.state.shape) 如果您打算顯示除實際 JS 對象之外的其他內容,則需要進行調整,以便顯示新組件或 HTML 元素而不僅僅是字符串。

未定義狀態,因為您使用了錯誤的語法“:”

將 {this.state.shape.bgColour} 用於 {this:state.bgColour}

您不能在 jsx 中顯示帶有 {} 的對象:

將 {this.state.shape} 更改為{this.state.shape} this.state.shape.size} 將{this:state.bgColour} {this.state.shape.size}更改為{this.state.shape.bgColour} ...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Timed Shapes</title>
    <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <style>
        .shape-item{
            padding: 10px;
            margin: 20px;
            display: inline-block;
            width: 100px;
            height: 100px;
            background-color: blue;
            border-radius: 50%;
        }
    </style>
</head>
<body>
<div class="shape-item">
    <div></div>
    <div></div>
</div>

<script type="text/babel">

    "use strict";

    var colours = ["#77b3d1", "#E94F37", "#1C89BF", "#A1D363", "#85FFC7", "#297373", "#FF8552", "#A40E4C", "#85AFC0", "#296573", "#AA8552", "#CC0E4C", "#567187", "#c6c976", "#967c64", "#e497ed", "#d24cff", "#e2ceb1", "#cc999e", "#97bf9a"];

    class Shapes extends React.Component{

        constructor(props){
            super(props);
            this.state = {
                shape: {
                    bgColour: colours[Math.floor((Math.random() * colours.length))],
                    size: 100,
                    perCent: "%50"
                }
            }
        }

        componentDidMount(){
            this.timerID = setInterval(() => this.updateShape(), 1000);
        }

        componentWillUnmount(){
            clearInterval(this.timerID);
        }

        updateShape(){
            let randomIndex = Math.floor((Math.random() * colours.length));
            this.setState(
                {
                    shape: {
                        bgColour: colours[Math.floor((Math.random() * colours.length))],
                        size: (Math.random() * 125),
                        perCent: (Math.random() * 100)
                    }
                }
            )
        }

        render(){
            console.log(this.state)
            var shapeStyle = {
                padding: 10,
                margin: 20,
                display: 'inline-block',
                backgroundColor: this.state.shape.bgColour,
                borderRadius: this.state.shape.perCent,
                width: this.state.shape.size,
                height: this.state.shape.size
            }
            return(
                <div style={shapeStyle}>
                    {this.state.shape.size}
                </div>
            )
        }
    }

    ReactDOM.render(<Shapes />, document.querySelector(".shape-item"));

    let shapesRender = [];

    for(let i=0; i < 60; i++){
        shapesRender.push(<Shapes key={i} />);
    }

    ReactDOM.render(shapesRender, document.querySelector(".shape-item"));

</script>
</body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM