【问题标题】:Reactjs: Loading view based on responseReactjs:根据响应加载视图
【发布时间】:2016-01-11 17:27:20
【问题描述】:

寻找一种方法让 React 处理一些 json,并根据响应加载视图。

例如:

1- React 有一个表单,响应发送到外部 API

2- API 处理输入,返回成功代码,除非存在验证问题,然后将响应发送回 React 应用

3- React 获取 json 响应,加载“成功”视图,或重新加载表单并输出错误

React 有没有一种简单的方法来处理这个问题?提前致谢!

【问题讨论】:

  • 基本上,您将不得不考虑 state填写表格发送表格/等待的三种情况下如何变化响应查看结果。然后视图对应用程序所处的状态做出反应。首先考虑数据结构/状态,然后我会阅读文档中的表单:facebook.github.io/react/docs/forms.html
  • 此外,“反应”状态的视图可以像if 语句一样简单,该语句根据所述状态呈现不同的组件。请记住,每次调用 setState 时都会调用 render

标签: javascript jquery json reactjs


【解决方案1】:

很简单...

基本上,您需要跟踪何时发起请求(发送数据)和何时完成请求(接收响应)。

根据返回的数据,您决定渲染什么...
看看这个例子(工作小提琴)

// 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'));

【讨论】:

    【解决方案2】:

    简单的方法是使用 API 回调函数中的 setState() 触发新状态,如下例所示,尽管我建议使用 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"));
    

    请注意,这是一个幼稚的示例,您仍应掩盖错误情况并构建逻辑以根据状态触发不同的视图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多