反应子prop更新不会导致父进程中的操作

时间:2017-08-03 22:52:44

标签: reactjs components onclicklistener

我知道我在这里犯了一个愚蠢的错误,但梳理我的代码,因为我可能无法弄清楚它为什么不起作用。让我从头开始

我试图在子组件中使用onClick侦听器来更改子项的支柱。子prop的更改应该导致父级状态的更改(通过使用单击处理函数),但由于某种原因,它不会。我可以确认孩子的道具正在改变,我可以确认父母的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 个答案:

答案 0 :(得分:1)

您没有调用父函数:

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

同样this.state.users为空,因此表永远不会呈现。

相关问题