ReactJS初学者状态已更新但在孩子中呈现

时间:2017-02-15 19:49:58

标签: javascript reactjs

在ReactJS上跟我一起初学者,所以我正在测试一些东西。

我创建了一个静态页面作为组件,在该组件中我加载了另一个自定义组件。

数据来自ajax调用,我更新了状态,但它没有更新子组件的视图。

静态页面

// Test.JS
import React from 'react';
import Layout from '../../components/Layout';
import Article from '../../components/Article';
import s from './styles.css';
import axios from 'axios';

class Test extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        article: null
    };

}

componentWillMount(){
    axios.get("https://gist.githubusercontent.com/koistya/a32919e847531320675764e7308b796a/raw/articles.json")
        .then(function(result) {
            var theArticle = result.data.filter((article) => article.title.split(' ').join('') === this.props.route.params.title.split(' ').join(''));
            this.setState({
                article: theArticle[0]
            })
        }.bind(this));
 }

render() {
    return (
        <Layout className={s.content}>
            <Article {...this.state.article} />
        </Layout>
    );
}

}

export default Test;

正如您所看到的,我使用ajax调用更新状态,但未更新子项。控制台登录文章显示一个空对象,因为它第一次呈现时内部没有任何内容。但在更新状态后,我希望它应该传递给孩子们。

import React from 'react';
import Link from '../Link';

class Article extends React.Component{

    componentDidMount() {
        console.log(this.props);
        window.componentHandler.upgradeElement(this.root);
    }

    componentWillUnmount() {
        window.componentHandler.downgradeElements(this.root);
    }

    render() {
        return (
            <div className="demo-card-wide mdl-card mdl-shadow--2dp" ref={node => (this.root = node)}>
                <div className="mdl-card__title">
                    <h2 className="mdl-card__title-text">{this.props.author}</h2>
                </div>
                <div className="mdl-card__supporting-text">
                </div>
                <div className="mdl-card__actions mdl-card--border">
                </div>
                <div className="mdl-card__menu">
                    <button className="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
                        <i className="material-icons">{this.props.title}</i>
                    </button>
                </div>
            </div>
    );
    }

}

export default Article;

所以我有以下问题:

1)首先,我正朝着正确的方向前进这是怎么做的? 2)构造函数不比willmount事件好吗? 2)为什么现在不更新子视图? 3)在这种情况下我是否应该使用道具或状态(在Test.js中)(在阅读之后仍然不确定)

1 个答案:

答案 0 :(得分:0)

我将其更改为componentDidMount,现在它更新了视图。

我不知道为什么它之前没有用!