如何管理 UI 反馈?

How to manage UI feedback?

是否有用于管理用户与各个组件的交互的既定模式,例如显示加载器微调器、在表单为 saving/loading 时禁用输入字段等?

我发现自己在商店中执行以下操作,以使组件与任何隐含状态在某种程度上脱钩:

function CampaignStore() {
    EventEmitter.call(this);

    AppDispatcher.register(payload => {
        switch (payload.type) {
            // [#1] ---------------v  (main action)
            case CampaignContants.SAVE:
                // [#2] ------------------------v  (prepare for the main action)
                this.emit(CampaignContants.WILL_SAVE);

                const data = payload.data;
                if (data.id) {
                    // [#3] ---v  (perform main action in store)
                    updateCampaign(payload.data).then(_ => {
                       // [#4] ------------------------v  (after main action)
                       this.emit(CampaignContants.DID_SAVE, 0)
                    });
                } else {
                    insertCampaign(payload.data).then(campaignId => this.emit(CampaignContants.DID_SAVE, campaignId));
                }
                break;
            // ...
        }
    }
}

基本上,我只是触发一个事件,说明某个动作即将发生,然后我执行该动作(进行 API 调用等),然后在该动作完成时发出另一个事件。

在组件内部,我可以只订阅一个 WILL_<action> 事件,呈现所有微调器等,然后在触发 DID_<action> 时清除屏幕。虽然这似乎行得通,但确实让人感觉很陈词滥调和重复,而且超级混乱(太多的状态只存在于根据动作的位置(在 WILL_<action> 和 * 之间)调整 UI DID_<action>.

// some component
var MyComponent = React.createClass({
   getInitialState: function () {
       return {
           items: [],
           loading: false,
           saving: false,
           checkingPasswordStrength: fase,
           // ...
       };
   },
   render: function(){
      return (
          <div>
             {this.state.loading && (
                 <p>Loading...</p>
             )}

             {!this.state.loading && (
                 // Display component in not-loading state
             )}
          </div>
      );
   }
});

我认为您最好使用 componentWillMountcomponentDidMountcomponentWillUpdatecomponentWillUnmount 等生命周期方法。使用这些方法,您可以检查 previous/current/next props/state(取决于方法)并对其做出响应。这样你的商店只处理你的状态,你的组件变得更纯粹。

此模式将帮助您让您的各个组件管理用户交互

var MyComponent = React.createClass({
getInitialState: function() {
  return {
    item: [],
    loading: true,
  };
},
componentDidMount: function() {
  //Make your API calls here
  var self = this;
  $.ajax({
    method: 'GET',
    url: 'http://jsonplaceholder.typicode.com/posts/1',
    success: function(data) {
      if (self.isMounted()) {
        self.setState({
          item: data,
          loading: false
        });
      }
    }
  });
},
render: function() {
  var componentContent = null;
  if (this.state.loading) {
    componentContent = (<div className="loader"></div>);
  } else {
    componentContent = (
      <div>
        <h4>{this.state.item.title}</h4>
        <p>{this.state.item.body}</p>
      </div>
    );
  }
  return componentContent;
}});

我们发现一个简单的加载容器组件在这里很有帮助。 所以像这样:

const LoadingContainer = React.createClass({
    getDefaultProps: function() {
      return {isLoadedCheck:(res) => res.data!=null }
    },
    getInitialState: function() {
      return {isLoaded:false, errors:[]}
    },
    componentDidMount: function() {
      if(this.props.initialLoad) { this.props.initialLoad(); }
      if(this.props.changeListener) { this.props.changeListener(this.onChange); }
    },
    onChange: function() {
      let res = this.props.loadData();
      this.setState({errors: res.errors, isLoaded: this.props.isLoadedCheck(res)});
    },
    render: function() {
      if(!this.state.isLoaded) {
        let errors = this.state.errors && (<div>{this.state.errors.length} errors</div>)
        return (<div>{errors}<LoadingGraphic /> </div>)
      }
      return <div>{this.props.children}</div>
    }
  });

  const Wrapper = React.createClass({
    getDefaultProps: function() {
      return {id:23}
    },
    render: function() {
      let initialLoad = () => someActionCreator.getData(this.props.id);
      let loadData = () => someStore.getData(this.props.id);
      let changeListener = (fn) => someStore.onChange(fn);
      return (<div><LoadingContainer initialLoad={initialLoad}
        changeListener={changeListener}
        loadData={loadData}
        isLoadedCheck={(res) => res.someData != null}><SomeComponent id={this.props.id} /></LoadingContainer></div>)
    }
  });

虽然它添加了另一个无状态包装器,但它提供了一种干净的方式来确保您的组件不只是在安装时加载以及显示 api 反馈等的公共位置。 在 React 14 中,这些纯无状态包装器得到了一些推动,性能改进即将到来,所以我们发现它可以很好地扩展