2016-06-19 59 views
1

我想创建HOC容器,它异步改变其状态。React HOC模式 - 处理异步方法

它将由两个组件使用。

这些组件订阅HOC异步方法的成功/失败并相应地更新其内部状态的最佳方法是什么?

回答

1

REDUX也可以使用。

  1. 你的精铸件必须是纯净的,可重用的不配合他们说出 原因应用程序将只是浪费系统资源做unnessary重新 渲染。国家的使用应尽可能有限。当您使用状态 时,您可能会冒险在组件的行为和呈现中引入若干 (有时是微妙的)错误。如果您决定使用属性来定义您的初始状态 状态;你的属性可能会改变,保留你的初始状态 根据陈旧的数据进行计算。您还需要在需要定义的属性与组件的内部状态之间引入紧密耦合 。
  2. 一般规则是不使用静态组件的状态。如果 组件不需要改变,根据外部因素,则 不使用状态。最好在 render()方法中计算渲染值。链接https://www.youtube.com/watch?v=ymJOm5jY1tQ

    https://medium.com/@mweststrate/3-reasons-why-i-stopped-using-react-setstate-ab73fc67a42e#.h3ioly71l

import React, {Component} from 'react'; 
 

 
export const fetchResource = msg => WrappedComponent => 
 
    class extends Component { 
 
    constructor(props){ 
 
     super(props); 
 

 
     this.state = { 
 
     resource: null, 
 
     msg: null 
 
     }; 
 
    } 
 

 
    componentDidMount(){ 
 
     this.setState({msg}) 
 
     axios.get('https://api.github.com/users/miketembos/repos') 
 
     .then((response)=>{ 
 
      console.log(response); 
 
      if(response.status===200){ 
 
      return response.data; 
 
      } else { 
 
      throw new Error("Server response wasn't ok"); 
 
      } 
 

 
     }) 
 
     .then((responseData)=>{ 
 
      this.setState({resource:responseData}); 
 
     }).catch((error)=>{ 
 
      this.props.history.pushState(null, '/error'); 
 
     }); 
 
    } 
 

 
    render(){ 
 
     const {resource} = this.state 
 
     //check if the resource is valid eg not empty or null 
 
     if(!resource){return <div>Loading...... or show any othe component you want load.....</div>} 
 
     return <Post {...this.props} {...resource } /> 
 
    } 
 
    }

high order component react with async call

enter image description here

+1

的代码,请不要发布图片,张贴代码,而不是。 – Bergi

+0

React/Facebook的原始参考模式,Flux也是一个很好的起点。 Redux是从它衍生出的许多* ux模式之一。 https://facebook.github.io/flux/docs/overview.html –