在reactjs中的render方法中访问状态值

时间:2017-02-08 10:57:52

标签: javascript reactjs

我有新的反应。试图将构造函数中的状态传递给我的渲染方法,但我的h1不可见,任何线索有什么问题?

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };
       //this worked!
        document.title = this.state.title;
    }

    render() {
        return(
            <div>
                <h1>{this.title}</h1>
            </div>
        )
    }
}

3 个答案:

答案 0 :(得分:1)

应该是

class Mod extends React.Component {
    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };
    }

    componentDidMount() {
        document.title = this.state.title;
    }

    render() {
        return(
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}

componentDidMount中更改文档标题 - 这意味着它将在组件准备好并可见时执行。

您不应该在构造函数中执行与浏览器相关的操作,因为在没有浏览器时可能会调用它(例如,当您使用node.js服务器端渲染渲染网站时)。只有在浏览器(和componentDidMount)可用时才会调用document

此外,您需要使用this.state.title代替this.titlethis与反应组件实例相关,this.state与您在构造函数中设置的状态相关。

答案 1 :(得分:1)

原因是你在状态中定义标题,将状态视为object,并且你在里面定义的所有变量都是关键值,要访问它们你必须像这样使用它: this.state.variable_name,使用此:

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world'
        };

    }

    render() {
        return(
            <div>
                <h1>{this.state.title}</h1>
            </div>
        )
    }
}

document.title='name'工作的原因是,您将其定义为全局变量,您可以直接通过document.title访问它们。

Doc:

  

Document是一个对象。全局对象document表示HTML文档   显示在当前浏览器窗口中。该   网络浏览器将具有JavaScript引擎。那个引擎将提供   具有一些运行时对象的开发人员,例如documentwindow   与...互动。

答案 2 :(得分:0)

如果您需要从state中获取更多值,并且这些值将在jsx中多次访问,那么您可以像这样。

class Mod extends React.Component {

    constructor(props) {
        super();
        this.state = {
           title : 'Hello world',
           name: "john doe",
           email: "johndoe@gmail.com",
        };

    }

    render() {
        let { title, name, email } = this.state;
        return(
            <div>
                <h1>{title}</h1>
                <h1>{name}</h1>
                <h1>{email}</h1>

                <h1>{title}</h1>
                <h1>{name}</h1>
                <h1>{email}</h1>

                <h1>{title}</h1>
                <h1>{name}</h1>
                <h1>{email}</h1>
            </div>
        )
    }
}