React router4:onClick Link组件上的更新状态

时间:2019-02-13 15:40:34

标签: javascript reactjs react-router-v4 reactstrap

我有一个Route组件,它将基于当前url呈现一行表,问题是我无法使用放在Link组件上的onClick更新状态,URL更改了,但状态仍然相同,因此渲染的行内容仍然相同,请看以下代码:

      <Route
        exact
        path={'/dashboard/:page'}
        render={() => (
          this.state.data &&
            data.map((data, index) =>
            <Row key={index}>
               <Col md="1" xl="1">{index + 1}</Col>
               <Col md="3" xl="4">{data.job_title}</Col>
               <Col md="2" xl="3">{data.city}</Col>
               <Col md="2" xl="2">{data.job_status}</Col>
               <Col md="2" xl="2"><a href="">{data.inbox.length > 1 ? data.inbox + ' Candidates' : data.inbox + ' Candidate'}</a></Col>
            </Row>
          )
        )}
      />
      <Route
        exact
        path={'/dashboard'}
        render={() => (
          this.state.data &&
            data.map((data, index) =>
            <Row key={index}>
               <Col md="1" xl="1">{index + 1}</Col>
               <Col md="3" xl="4">{data.job_title}</Col>
               <Col md="2" xl="3">{data.city}</Col>
               <Col md="2" xl="2">{data.job_status}</Col>
               <Col md="2" xl="2"><a href="">{data.inbox.length > 1 ? data.inbox + ' Candidates' : data.inbox + ' Candidate'}</a></Col>
            </Row>
          )
        )}
      />
    </div>
    <div style={{display: 'flex', justifyContent: 'center'}}>
      <Link onClick={() => {this.setState({currentPage: this.state.currentPage + 1, data: dataMock.data[this.state.currentPage + 1]})}} to="/dashboard/1">
        <Button style={{margin: '20px'}}>Page + 1</Button>
      </Link>
      <Link onClick={() => {this.setState({currentPage: this.state.currentPage - 1, data: dataMock.data[this.state.currentPage - 1]})}} to='/dashboard/2'>
        <Button style={{margin: '20px'}}>Page - 1</Button>
      </Link>
    </div>

问题是我如何用新状态更新状态?似乎状态没有更新,我做错了吗?我对之前找到的解决方案有点困惑,这里是链接:React to url change within component with React Router 4?

1 个答案:

答案 0 :(得分:0)

如果这是一个好习惯,我不习惯。但是更简单的解决方法是 将click事件添加到按钮,然后在setState的回叫this.props.history.push('Route')

上执行onClick,执行setState

例如,

takeUserToPage = () => {
  this.setState({currentPage: this.state.currentPage + 1, data: 
   dataMock.data[this.state.currentPage + 1]}, () => {
   this.props.history.push('Route')
  });
}

//inside your return
 <Button style={{margin: '20px'}} onClick={this.takeUserToPage}>Page + 1</Button>