在初始渲染之前重新激活挂载状态或保持原样

Reactjs mounting state before initial render or keep as is?

本文关键字:状态 激活 新激活      更新时间:2023-09-26

此处初始渲染的状态是初始状态。 我正在使用组件将挂载(),但是如果不首先检查组件是否已挂载,它将无法工作。 使用 rawMarkup() 时的结果是一个空的初始状态对象。 一切都在重新渲染时正常运行,但想知道为什么状态中的 post 对象在初始渲染时仍然是空的。 有没有更好的方法来实现这一点? 谢谢。

var Post = React.createClass({
propTypes: {
    source: React.PropTypes.string.isRequired,
},
getInitialState: function() {
    return {
        post: {}
    };
},
getDefaultProps: function() {
    return {
        source: 'http://localhost:3000/api/posts/' + postSlug
    };
},
componentWillMount: function() {
    $.get(this.props.source, function(result) {
        if (this.isMounted()) {
            this.setState({post: result});
        }
    }.bind(this));
},
rawMarkup: function() {
    console.log(this.state.post);
    var rawMarkup = marked(this.state.post.body || '', {sanitize: true});
    return { __html: rawMarkup };
 },
render: function() {
    var post = this.state.post;
    var date = moment(post.date).format('MM[/]DD[/]YYYY');
    return (
        React.createElement('div', {style: {marginLeft: '115px'}},
            React.createElement('h1', {style: {marginTop: '50px'}}, post.title),
            React.createElement('h5', {style: {marginBottom: '25px'}}, date),
            React.createElement('span', {dangerouslySetInnerHTML: this.rawMarkup()})
        )
    );
}

});

默认情况下,jQuery get 请求是异步的,因此初始呈现发生在请求完成并调用 this.setState({post: result}) 之前。 你可以使get请求同步(如何让jQuery执行同步而不是异步的Ajax请求?),或者找到一种方法来优雅地处理初始渲染上没有数据(推荐)。