2017-05-31 19 views
0
render() { 
    console.log(this.state.myStateValue); // I see this on the console 
    var test = configOptions ? 
    Object.keys(configOptions).map(function(key) { 
     console.log('test'); // I see this on the console 
     console.log(this.state.myStateValue); // Getting Uncaught TypeError: Cannot read property 'state' of undefined 
    } 
    return() {...} 
} 

我在做什麼錯?Object.keys中找不到狀態

謝謝!

+1

的可能的複製[?如何進入回調中正確的\'這\'上下文(HTTPS ://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – noahnu

回答

1

試試這個:

Object.keys(configOptions).map(function(key) { 
    console.log('test'); 
    console.log(this.state.myStateValue); 
}.bind(this)) 

或更好,如果你有ES6

Object.keys(configOptions).map((key) => { 
    console.log('test'); 
    console.log(this.state.myStateValue); 
}) 
+2

我剛剛複製了OP的片段。想必他只是想測試'this.state'的可見性,稍後會在循環中做更多的事情。 – pscl

+0

@ user1628461工作!謝謝!!我想我需要更多地瞭解這個 –

+0

@ user1628461哦,是的,你是對的,我的錯誤。 – noahnu