2017-05-05 52 views
0

我想根據我發送給組件的專業人員動態設置類。不知何故,我得到錯誤「無法讀取屬性'未定義狀態」。 我想這不存在,當我嘗試設置類的狀態類作爲一個類?在使用組件的渲染之前,我是否必須重新綁定它?設置類使用狀態如果其他與反應獲取狀態未定義的錯誤

var ReactDOM = require('react-dom'); 
var React = require('react'); 

class Button extends React.Component { 
    constructor(props) { 
     super(props); 
     console.log("BUTTON") 
     console.log(props); 

     this.state = { 
      class: "small-button" 
     }; 

     props.options.map(function (option) { 
      if (option.Description > 10) { 
       this.setState({ 
        class: "big-button" 
       }); 
      } 
     }); 
     console.log("STATE: " + this.state.class); 
    } 

    render() { 
     if (this.props.options) { 
      return (<div> { 
       this.props.options.map(function (option) { 
        return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div> 
       }) 
      } 
      </div> 
      ) 
     } else { 
      return <div>No options defined</div> 
     } 
    } 
} 

module.exports = Button; 
+0

其的結合問題,使用'箭頭function':'this.props.options.map((選項)=> {.....'**一個建議:**不要將邏輯放入'constructor'中,也不要使用'setState',使用生命週期方法。將該邏輯放在'componentDidMount'方法或'componentWillMount'方法內:) –

+0

謝謝,但我超級新的反應,你能給我一個更大的代碼示例你是什麼意思的箭頭功能? –

回答

1

這是有約束力的問題,您需要bind功能使用this關鍵字(正確的上下文中)內部的。

使用此:

render() { 
     if (this.props.options) { 
      return (<div> { 
       this.props.options.map((option) => { 
        return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div> 
       }) 
      } 
      </div>) 
     } else { 
      return <div>No options defined</div> 
     } 
    } 

檢查這個答案詳細的arrow function and this keyword

一個建議:不要把邏輯裏面constructor和不做setState還使用生命週期的方法那。將該邏輯放在componentDidMount方法或componentWillMount方法內。

像這樣:

class Button extends React.Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      class: "small-button" 
     }; 
    } 

    componentDidMount(){ 
     this.props.options.forEach((option) => { 
      if (option.Description > 10) { 
       this.setState({ 
        class: "big-button" 
       }); 
      } 
     }); 
    } 

    render() { 
     if (this.props.options) { 
      return (
       <div> 
       { 
        this.props.options.map((option) => { 
         return <div className={ this.state.class === 'big-button' ? 'option-button big-button' : 'option-button small-button'} key={option.Id}> {option.Description}</div> 
        }) 
       } 
       </div> 
      ) 
     }else{ 
      return <div>No options defined</div> 
     } 
    } 
} 
+0

所以this.props.options.map((選項)=> {而不是this.props.options.map(函數(選項){0}綁定新的狀態? –

+0

@DanielGustafsson它不會'綁定'狀態',''綁定'context'意味着如果你不綁定,'this'關鍵字不會引用'react class component'並且'this.state'將會是undefined,你的代碼也可以工作只需刪除映射體內的'this'關鍵字,只需返回一個跨度就不會拋出錯誤 –

+0

@DanielGustafsson檢查更新的答案,附上一個非常有用的鏈接,它將幫助您瞭解此關鍵字的作用。 –