Reactjs:基于响应加载视图
Reactjs: Loading view based on response
React正在寻找一种方法来处理一些json,并根据响应加载视图。
例如:
1-React有一个表单,响应发送到外部API
2-API处理输入,除非存在验证问题,否则返回成功代码,并将响应发送回React应用程序
3-React获取json响应,加载"成功"视图,或者重新加载表单并输出错误
React有没有一种简单的方法来处理这个问题?提前感谢!
非常简单。。。
基本上,您需要跟踪何时启动请求(发送数据)以及何时完成请求(接收响应)。
根据返回的数据,您可以决定渲染什么
看看这个例子(工作小提琴)
// In this example, we are using JSONPlaceholer service do real
// request and receive response;
const root = 'http://jsonplaceholder.typicode.com';
const Success = () => (<div>Success!</div>);
const Error = () => (<div>Error! Fix your data!</div>);
const Form = React.createClass({
getInitialState() {
return {
processing: false,
result: undefined,
};
},
submit(event) {
this.setState({ processing: true });
event.preventDefault();
fetch(`${root}/posts`, {
method: 'POST',
data: {
// your data here...
}
})
.then(response => {
// We simulate succesful/failed response here.
// In real world you would do something like this..
// const result = response.ok ? 'success' : 'error';
const processing = false;
const result = Math.random() > 0.5 ? 'success' : 'error';
this.setState({ result, processing });
});
},
render() {
const { result, processing } = this.state;
if (result === 'success')
return <Success />;
return (
<form>
Form content here<br/>
<button onClick={this.submit}>
{ processing ? 'Sending data...' : 'Submit' }
</button>
{ result === 'error' && <Error /> }
</form>
);
},
});
render(<Form />, document.getElementById('root'));
简单的方法是使用setState()从API回调函数触发新状态,如下面的示例,尽管我建议使用Redux等库进行状态管理。
var MainComp = React.createClass({
getInitialState: function() {
return {someProp: ""}
},
callAPI: function() {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
this.setState({someProp: data.body})
}.bind(this));
},
render: function(){
return (
<div>
<h2>{this.state.someProp}</h2>
<button onClick={this.callAPI}>Async</button>
</div>
)
}
});
React.render(<MainComp/>, document.getElementById("app"));
请注意,这是一个天真的例子,您仍然应该掩盖错误案例,并构建一个基于状态触发不同视图的逻辑。
相关文章:
- Nodejs服务器:加载资源失败:服务器的响应状态为404(未找到)
- 如何放置单独的ajax调用,使页面的一部分完全响应,而另一部分仍在加载
- 如何从ajax响应中重新加载整个页面
- ng高图表的响应行为,加载时隐藏编译的ng点击xAxis标签
- 带Jquery的wep API,加载资源失败:服务器响应状态为404(未找到)
- 加载超链接页面后如何响应事件
- 页面加载时未定义的 ajax 响应
- iframe响应为302时重新加载应用程序
- 如何记录Apache Cordova应用程序中加载的iframe的http响应
- 将 Ajax 响应数据加载到挖空数组中
- 无法加载响应
- 在页面加载时关闭响应式菜单
- 实际响应加载内容的预加载器
- 更改 URL 并使用 AJAX 获取响应加载新页面的最佳方法是什么
- ReactJS 在服务器响应加载之前将 props 发送到子级错误
- Reactjs:基于响应加载视图
- 将AJAX响应加载到浏览器中(不带jQuery)
- 将ajax响应加载到数据表中
- 将数据从Form Panel响应加载到网格中
- 使用jQuery在每个链接后将PHP响应加载到DIV中