簡體   English   中英

雖然this.state是一個Javascript對象,但即使將狀態傳遞給有數據的狀態,為什么狀態也為null?

[英]while this.state is a Javascript object , why is state null even after passing into it a state that has data?

我有以下代碼(見下文)

我希望它顯示由firstName和lastName組合而成的用戶名。 為什么下面的代碼不起作用?

我希望它能顯示

歡迎Daggie Blanqx!

class Header extends React.Component{

    constructor(props){
        super(props);
        this.state = {
            firstName : 'Daggie',
            lastName :  'Blanqx',
            userName : ()=>(this.state.firstName + this.state.lastName)
        }


    }

    render(){
        return(
            <div>
                <p> Welcome {this.state.userName} !</p>
            </div>
            )
    }
}

您缺少()

<p> Welcome {this.state.userName()} !</p>

也不需要為此定義函數直接獲得這樣的結果

<p>Welcome , {this.state.firstName} {this.state.lastName} !</p>

似乎您正在向狀態插入一個函數,因此您需要調用它來獲取結果。 通常不建議將這樣的功能置於狀態。 但是,如果您仍然想使用該方法,請嘗試以下操作:

<p>Welcome , {this.state.userName()} !</p>

更好的方法是從狀態中刪除該函數並執行以下操作:

getUserName() {
   return this.state.firstName + this.state.lastName
}

然后在您的模板中:

<p>Welcome , {this.getUserName()} !</p>

在您的示例中,您正在訪問函數this.state.userName您需要像this.state.userName()這樣調用它
this.state.userName將返回您需要在函數末尾添加()function變量,以獲取該函數的return
您了解為什么它不起作用
嘗試避免在狀態對象中使用方法

它應該引發錯誤,因為您正在嘗試與狀態進行交互,但狀態尚未初始化。 為此,請使用componentDidMount() + prevState或將其放入render()

變體1

import React, { Component } from 'react'

export default class Header extends Component {

    constructor(props) {
        super(props)
        this.state = {
            firstName : 'Daggie',
            lastName :  'Blanqx'
        }


    }

    render() {
        return(
            <div>
                <p> Welcome {this.state.firstName + this.state.lastName} !</p>
            </div>
            )
    }
}

變體2

import React, { Component } from 'react'

export default class Header extends Component {

    constructor(props) {
        super(props)
        this.state = {
            firstName : 'Daggie',
            lastName :  'Blanqx',
            fullName: ''
        }
    }
    componentDidMount() {
      this.setState(prevState => ({
        fullName: prevState.firstName + prevState.lastName
      }))
    }

    render() {
        return(
            <div>
                <p> Welcome {this.state.fullName} !</p>
            </div>
            )
    }
}

暫無
暫無

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

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