如何在reactjs中访问componentWillMount()中的变量值

时间:2018-04-25 06:42:53

标签: javascript reactjs react-lifecycle

我在componentWillMount内分配值,如下所示

componentWillMount() {
    /*this.props.fetchMetaData(this.props.url);*/
    axios.get(`https://api.microlink.io/?url=${this.props.url}`)
        .then(res => {
            this.metaData = res;
            console.log("99999999999 ", this.metaData.data.data);
            this.image = this.metaData.data.data.image.url;
            this.title = this.metaData.data.data.title;
            this.description = this.metaData.data.data.description;
            this.metaurl = this.metaData.data.data.url;
            console.log("title ", this.title);
        });
}

我试图在render()内显示值,如下所示。

render() {
    console.log("title ", this.title);
    return (
        <div>
            <a className="previewUrlContainer float_left unchange_div border"
               href={metaurl}
               target="_blank">
                <img className="previewImage margin_bottom10px" src={this.image}></img>
                <div className="margin_bottom10px font_bold">{this.title}</div>
                <div className="margin_bottom10px medium_font">{this.description}</div>
                <div className="margin_bottom10px small_font">{this.metaurl}</div>
            </a>
        </div>
    );
}

但即使我已检查componentWillMount内的所有值,我仍会收到未定义的值。如何在componentWillMount中使用render()内的值。

2 个答案:

答案 0 :(得分:3)

由于您在componentWillMount中进行了异步调用,因此您的响应仅在初始渲染之后就绪,当您只是设置类变量时,不会调用重新渲染,因此结果不会反映在UI中。您应该使用state来存储数据。此外,您必须在componentDidMount生命周期中调用API。您可以查看此内容以获取更多详细信息

Use componentWillMount or componentDidMount lifecycle functions for async request in React

state= {
    image: '',
    title: '',
    description: '',
    metaurl: ''
}
componentDidMount() {


    /*this.props.fetchMetaData(this.props.url);*/
    axios.get(`https://api.microlink.io/?url=${this.props.url}`)
        .then(res => {

            this.setState({
                image: res.data.data.image.url;
                title: res.data.data.title;
                description : res.data.data.description;
                metaurl : res.data.data.url;
           })

        })

    }

render() {

    return (

        <div>

            <a className="previewUrlContainer float_left unchange_div border"
               href={metaurl}
               target="_blank">

                <img className="previewImage margin_bottom10px" src={this.state.image}></img>
                <div className="margin_bottom10px font_bold">{this.state.title}</div>
                <div className="margin_bottom10px medium_font">{this.state.description}</div>
                <div className="margin_bottom10px small_font">{this.state.metaurl}</div>


            </a>

        </div>
    );
}

答案 1 :(得分:1)

您应该将这些数据存储在该状态中。在<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>中致电setState(建议更改为componentWillMount以获得更明确的意图。)

演示:

componentDidMount