2016-06-19 60 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 –