2016-11-16 45 views
3

我很難理解爲什麼我的props.updateBuilding不工作。反應道具沒有定義

下工作時的道具渲染方法

class Buildings extends Component { 
    constructor(props) { 
     super(props); 
    } 

    componentWillMount() { 
    this.props.fetchBuildings(); 
    } 

    renderBuildings(building) { 
    return (
     <div> 
      <p> {building.name}</p> 
     </div> 
    ); 
    } 


    render() { 
    return (
     <div> 
     {this.props.buildings.map(this.renderBuildings)} 
     <button type="button" className="btn btn-success" onClick={this.props.updateBuilding.bind(this, 1)}>Edit</button> 
     </div> 
    ); 
    } 
} 

function mapStateToProps(state) { 
    return { buildings: state.buildings.all }; 
} 
function mapDispatchToProps(dispatch){ 
    return bindActionCreators({ fetchBuildings, updateBuilding}, dispatch); 
} 

內,但是,當我把this.props.updateBuilding像下面的renderBuildings方法...

renderBuildings(building) { 
    return (
     <div> 
      <p> {building.name}</p> 
      <button type="button" className="btn btn-success" onClick={this.props.updateBuilding.bind(this, building.id)}>Edit</button> 
     </div> 
    ); 
    } 

我得到的錯誤:

Cannot read property 'props' of undefined 

看起來道具updateBuildings不能成立d當它在renderBuildings方法中時,我不知道是什麼導致了這一點。

回答

6

你想念這個錯誤。 props未定義,所謂的props未定義,即this關鍵字。您可以手動通過傳遞第二個參數

this.props.buildings.map(this.renderBuildings, this)

設置地圖功能的情況下或結合內嵌

this.props.buildings.map(this.renderBuildings.bind(this))

2

嘗試:

this.props.buildings.map(this.renderBuildings.bind(this)) 
7

在我的案例,我忘了將props作爲參數添加到構造函數中。

constructor(props) { 
    super(props); 
}