在初始渲染之前重新激活挂载状态或保持原样
Reactjs mounting state before initial render or keep as is?
此处初始渲染的状态是初始状态。 我正在使用组件将挂载(),但是如果不首先检查组件是否已挂载,它将无法工作。 使用 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请求?),或者找到一种方法来优雅地处理初始渲染上没有数据(推荐)。
相关文章:
- 事件和状态
- 获取选择框的状态
- 激活chrome上的chrome.notifications对象
- 提示使用服务器端事件处理程序激活JavaScript
- 在单击按钮时激活按钮的悬停状态,直到单击另一个按钮(Javascript/JQuery)
- 需要在悬停时激活动作,并在7秒内返回到原始状态
- Jquery:更改选择框值并激活单击状态
- 当用户将鼠标悬停在 Chrome 或 Firefox 中的链接上时,悬停状态未激活
- 当目标处于顶部滚动状态时,如何从菜单中激活项目
- 在角度状态更改后激活特定选项卡
- 角度 SPA 未显示状态激活的 API 数据
- 在初始渲染之前重新激活挂载状态或保持原样
- 单击链接两次以使用ui路由器激活状态
- 我想在从下拉列表中选择其他选项时激活一个文本框,否则它将保持不活动状态
- 激活状态在错误的按钮
- 如何判断谷歌翻译是否处于激活状态?
- 如何为多个 url 状态设置仅使用反应路由器激活一个链路
- 启用:在IE7中使用jQuery的激活状态
- 在激活状态下创建链接
- Angular-ui Router会并行地激活两个状态