Reactjs:基于响应加载视图

Reactjs: Loading view based on response

本文关键字:响应 加载 视图 于响应 Reactjs      更新时间:2023-09-26

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"));

请注意,这是一个天真的例子,您仍然应该掩盖错误案例,并构建一个基于状态触发不同视图的逻辑。