Reactjs 反应:在请求ajax后设置状态时,如何防止闪烁?
下面的代码是我写的Reactjs 反应:在请求ajax后设置状态时,如何防止闪烁?,reactjs,user-experience,Reactjs,User Experience,下面的代码是我写的PostView组件,它显示了博客上的一篇文章。我决定将ajax调用放在componentDidMountcycle上,PostView组件通过请求GET/blog?post=id获取数据并设置状态。我听说不应该在组件willmount上设置状态。但这会显示20毫秒或更长时间内的空白页。。。(我尝试将ajax调用放在构造函数上,但它没有呈现。我选择显示加载组件,这是微调器动画,但仍然很尴尬。) 从“React”导入React; 从“道具类型”导入道具类型; 从“jquery”导
PostView
组件,它显示了博客上的一篇文章。我决定将ajax调用放在componentDidMount
cycle上,PostView组件通过请求GET/blog?post=id
获取数据并设置状态。我听说不应该在组件willmount
上设置状态。但这会显示20毫秒或更长时间内的空白页。。。(我尝试将ajax调用放在构造函数上,但它没有呈现。我选择显示加载组件,这是微调器动画,但仍然很尴尬。)
从“React”导入React;
从“道具类型”导入道具类型;
从“jquery”导入美元;
进口{
加载,
}来自“../components”;
类PostView扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
标题:“”,
内容:“”,
fetchStatus:'INIT',
};
}
componentDidMount(){
const thisComponent=this;
const id=this.props.match.params.id;
$.get(`/blog?post=${id}`)
.完成((数据)=>{
常量{title,content}=data[0];
setState({title,content,fetchStatus:'OK'});
})
.fail(()=>{thisComponent.setState({fetchStatus:'fail'});});
}
render(){
if(this.state.fetchStatus!=='OK'){
返回
}
返回(
{this.state.title}
{this.state.content}
);
}
}
PostView.propTypes={
匹配:PropTypes.shape({
参数:PropTypes.object,
isExact:PropTypes.bool,
路径:PropTypes.string,
url:PropTypes.string,
}),
};
PostView.defaultProps={
匹配:{
参数:{},
isExact:'假',
路径:“”,
url:“/”,
},
};
导出默认后视图;
除非得到服务器的响应,否则您将无法看到任何内容,componentDidMount是接收API请求的理想场所。在您的情况下,您应该显示一个加载微调器或其他东西,以指示调用尚未在一段时间内恢复response@ShubhamKhatri你的意思是没有其他方法可以将ajax调用放入生命周期,所以我应该找到另一种方法来隐藏闪烁?componentDidMount是进行ajax调用的正确位置,但是,在您的响应可用之前,您无法执行任何操作,因此您必须使用微调器或加载消息。您可以使用更平滑的加载屏幕使其看起来更好。查看这篇文章:。自我回答:使用单个数据存储(例如Redux或mobX)并远离从视图逻辑获取API。除非从服务器获得响应,否则您将无法看到任何内容,componentDidMount是接收API请求的理想位置。在您的情况下,您应该显示一个加载微调器或其他东西,以指示调用尚未在一段时间内恢复response@ShubhamKhatri你的意思是没有其他方法可以将ajax调用放入生命周期,所以我应该找到另一种方法来隐藏闪烁?componentDidMount是进行ajax调用的正确位置,但是,在您的响应可用之前,您无法执行任何操作,因此您必须使用微调器或加载消息。您可以使用更平滑的加载屏幕使其看起来更好。检查这篇文章:。自我回答:使用单个数据存储(例如Redux或mobX)并避免从视图逻辑获取API。
import React from 'react';
import PropTypes from 'prop-types';
import $ from 'jquery';
import {
Loading,
} from '../components';
class PostView extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
content: '',
fetchStatus: 'INIT',
};
}
componentDidMount() {
const thisComponent = this;
const id = this.props.match.params.id;
$.get(`/blog?post=${id}`)
.done((data) => {
const { title, content } = data[0];
thisComponent.setState({ title, content, fetchStatus: 'OK' });
})
.fail(() => { thisComponent.setState({ fetchStatus: 'FAIL' }); });
}
render() {
if (this.state.fetchStatus !== 'OK') {
return <Loading />
}
return (
<div className="container padding">
<h1>{this.state.title}</h1>
<p>{this.state.content}</p>
</div>
);
}
}
PostView.propTypes = {
match: PropTypes.shape({
params: PropTypes.object,
isExact: PropTypes.bool,
path: PropTypes.string,
url: PropTypes.string,
}),
};
PostView.defaultProps = {
match: {
params: {},
isExact: 'false',
path: '',
url: '/',
},
};
export default PostView;