2016-10-12 45 views
2

反應,fetch()開發的UI和我落得這樣做的:我真的需要使用forceUpdate與獲取API和我使用ReactJS

getOperatorsList: function (obj) { 
    fetch('http://x.x.x.x/operators.list', 
     { 
      method: 'GET', 
      credentials: 'include' 
     } 
    ).then(function (response) { 
      return response.json() 
     }).then(function (json) { 
     if (json.statusCode === 3) { 
      cookieService.unsetCookie('sessId'); 
     } 
     obj.setState({ data: json },() => obj.forceUpdate()); 
    }).catch(function (ex) { 
     console.log('parsing failed', ex); 
    }) 

} 

這就是所謂的在我的組件運營商,看起來像這

var Operators = React.createClass({ 

    getInitialState: function() { 
     return { 
      data: [{ "data": "Loading" }] 
     } 
    }, 

    componentDidMount: function() { 
     operatorsService.getOperatorsList(this); 
    }, 

    render: function() { 
     return (
      <div> 
       <Row > 
        <Col> 
         <DataTablesCustom data={this.state.data} /> 
        </Col> 
       </Row> 
      </div> 
     ); 
    } 
}); 

我已經有了一看this question,並且代碼不會爲我工作。

這工作正常,但我真的需要使用forceUpdate()還是我有辦法讓代碼「更清潔」?

編輯:有一個setState在子組件中看起來像這個this.setState({stuff: stuff}, this.function()});。在將setState更改爲this.setState({stuff: stuff},() => this.function()});後,我能夠刪除forceUpdate()

+0

它的工作原理沒有? –

+0

沒有它,我想要的數據沒有顯示頁面加載時。 – Harmeko

+0

所以你有你的答案,你必須使用它;)(這段代碼看起來很清楚) –

回答

0

爲了讓您的代碼工作,你可以嘗試做到這一點的服務:

obj.setState.bind(obj)({ data: json }); 

然而,沒有必要對組件對象傳遞給你的服務。可以說,這並不是一個好主意,因爲當你不需要的時候你可以把它們聯繫起來。讓組件調用你的服務,然後再決定如何處理數據做:

getOperatorsList: function() { 
    return fetch('http://x.x.x.x/operators.list', { 
     method: 'GET', 
     credentials: 'include' 
    }).then(function (response) { 
     return response.json() 
    }).then(function (json) { 
     if (json.statusCode === 3) { 
      cookieService.unsetCookie('sessId'); 
     } 
     return json; 
    }).catch(function (ex) { 
     console.log('parsing failed', ex); 
    }) 

} 
在組件

然後:

componentDidMount: function() { 
    operatorsService.getOperatorsList() 
    .then(function (json) { 
     this.setState({ data: json }); 
    }.bind(this)) 
} 
+0

你忘了返回'getOperatorsList'的承諾 –

+0

我得到'未捕獲TypeError:無法讀取屬性'然後'未定義'和我引用的問題做了這加在fetch()之前添加了一個返回,但這不起作用無論是。我得到了和以前一樣的行爲。 – Harmeko

+0

@ Steeve Pitis你是對的,編輯。 –