我在使用以前的狀態設置組件的狀態時遇到問題。 這裏的代碼 - https://gist.github.com/red4211/1b8ae503fc76b7a3771d45eca0b81a19React,在設置組件狀態時遇到問題
評論部分是錯誤的,但希望能給你我想要在這裏做的想法。
請幫助我,我卡住了。
感謝您的幫助傢伙,一切都在工作!
我在使用以前的狀態設置組件的狀態時遇到問題。 這裏的代碼 - https://gist.github.com/red4211/1b8ae503fc76b7a3771d45eca0b81a19React,在設置組件狀態時遇到問題
評論部分是錯誤的,但希望能給你我想要在這裏做的想法。
請幫助我,我卡住了。
感謝您的幫助傢伙,一切都在工作!
它的結合問題,以解決使用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);
您需要綁定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));
})