2017-05-23 105 views

回答

0

它的結合問題,以解決使用arrow function

this.props.list.map((current) => { 
    api.getStreamInfo("https://wind-bow.glitch.me/twitch-api/channels/"+current) 
    .then((response) => { 
     console.log(response.data); 
     let streamObj = this.state.streamObj.slice(); 
     streamObj.push(response.data); 
     this.setState({ streamObj }) 
    }); 
}) 

,或者您可以使用spread operator也:

this.props.list.map((current) => { 
    api.getStreamInfo("https://wind-bow.glitch.me/twitch-api/channels/"+current) 
    .then((response) => { 
     console.log(response.data);   
     this.setState((prevState) => ({ streamObj: [...prevState.streamObj, response.data] })) 
    }); 
}) 

的Array.push不會返回更新array,它會返回僅限推送項目,因此首先將array複製到一個單獨的變量中,然後使用setState更新該值。

檢查這個片段:

let a = [1,2]; 
 

 
let b = [...a, 3]; 
 

 
console.log('a:', a); 
 
console.log('b:', b);

1

您需要綁定promise功能,然後update狀態。利用concat因爲它返回一個新的數組

做到像

this.props.list.map(function(current){ 
    api.getStreamInfo("https://wind-bow.glitch.me/twitch-api/channels/"+current) 
     .then(function(response){ 
     console.log(response.data); 
     this.setState(function(prevState, props){ 
      streamObj: prevState.streamObj.concat(response.data); 
     }) 
     }.bind(this)); 
    }) 

this.props.list.map(function(current){ 
    api.getStreamInfo("https://wind-bow.glitch.me/twitch-api/channels/"+current) 
     .then(function(response){ 
     console.log(response.data); 
     var streamObj = [...this.state.streamObj]; 
     streamObj.push(response.data) 
     this.setState({streamObj}) 
     }.bind(this)); 
    }) 
相關問題