2017-08-03 57 views
0

我知道我在這裏犯了一個愚蠢的錯誤,但梳理我的代碼,因爲我可能我不明白爲什麼它不工作。讓我從頭開始反應兒童道具更新不會導致父母的行爲

我想在一個子組件中的onClick監聽器來改變孩子的道具。子道具的改變應該引起父級狀態的改變(通過使用點擊處理函數),但由於某種原因,它不是。我可以確認孩子的道具正在改變,我可以確認父母的changeState函數沒有被觸發。有人可以告訴我爲什麼嗎?這裏是代碼:

class Table extends React.Component{ 
    constructor(props){ 
    super(props) 
    this.ajaxCall = this.ajaxCall.bind(this) 
    this.state = { 
     query : 'https://fcctop100.herokuapp.com/api/fccusers/top/recent', 
     users : undefined 
    } 
    this.changeQueryState = this.changeQueryState.bind(this) 
    } 


    changeQueryState(query){ 

    if (query != this.state.query){ 
     this.setState({ 
     query : query 
     }) 
    } 
    } 

    render(){ 
     if (this.state.users){ 
    return (
     <table className='table table-bordered table-striped'> 
     <TableToolbar onClick={this.changeQueryState}/> 
     <Users rows={this.state.users}/> 
     </table> 
    ) 
    }  else{ 
     return null 
     } 
    } 
} 




class TableToolbar extends React.Component{ 
    constructor(props){ 
    super(props) 
    this.onClickHandler = this.onClickHandler.bind(this) 
    } 

    onClickHandler(clicked){ 
    if (clicked.target.id === "30"){ 
     this.props.onClick = 
    'https://fcctop100.herokuapp.com/api/fccusers/top/recent' 
     } else if (clicked.target.id == "alltime"){ 
     this.props.onClick = 
'https://fcctop100.herokuapp.com/api/fccusers/top/alltime' 
     } 
    } 

    render(){ 
    return (
     <thead> 
      <tr className="row m-0"> 
      <th className="col-1">#</th> 
      <th className="col-6">Camper Name</th> 
      <th className="col-3"><p className="clickable" id="30" 
onClick={this.onClickHandler}>Points In Past 30 Days</p></th> 
      <th className="col-2"><p className="clickable" 
id="alltime" onClick={this.onClickHandler}>Points Alltime</p></th> 
      </tr> 
     </thead> 
    ) 
    } 
} 

Table類中的changeQueryState是什麼不工作。爲什麼?

回答

1

你是不是調用父函數:的

this.props.onClick('<url>')代替this.props.onClick = '<url>'

而且this.state.users是空的,所以該表將永遠不會渲染。

+0

不錯,知道我錯過了一件容易的事。此外,我有this.state.users和整個其他組件,我只是沒有顯示它,因爲它不涉及我遇到的問題。謝謝回答! –

+0

我還有一個問題,我一直在努力,也許你可以幫助我。當我想要進行另一個Ajax調用以更新桌面上的用戶時。我目前在componentDidMount中調用ajax,但只發生一次。當查詢狀態發生變化時,什麼樣的方法可以實現ajax調用? –