反应路由器标识符重新呈现

时间:2017-07-30 08:35:27

标签: javascript node.js reactjs react-router babel

我使用这样的结构:

<Switch>
  <Route
         exact
         path="/log-out"
         component={ requireLogin(Logout) } />
  <Route
         exact
         path="/sign-in"
         component={ requireNotLogin(LoginPage) } />
  <Route
         exact
         path="/sign-up"
         component={ requireNotLogin(SignupPage) } />
  <Route
         path="/:user"
         component={ UserPage } />
  <Route
         exact
         component={ NotFoundPage } />
</Switch>

但用户标识符未多次呈现

class UserPage extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isLoading: true,
      user: false
    }
    this.getUserPage = this.getUserPage.bind(this)
  }
  componentDidMount() {
    this.getUserPage()
  }
  getUserPage() {
    this.props.getUserPage(this.props.match.params.user).then((res) => {
      this.setState({
        isLoading: false,
        user: res.data.user
      })
    }, (err) => {
      this.setState({
        isLoading: false,
        user: false
      })
    })
  }
  render() {
    return (
      <div onMouseOver={ this.getUserPage }>
        { this.state.isLoading ?
          <div class="progress">
            <div class="indeterminate"></div>
          </div> : this.state.user ? <div></div> : <div>
                                                     User not found
                                                   </div> }
      </div>
    )
  }
}

我尝试过componentDidUpdate()等。但有些得到无限循环或者它被渲染一次 this.props.getUserPage():

import axios from 'axios'

export function getUserPage(identifier) {
  return dispatch => {
    return axios.get('/Q/userPage/' + identifier)
  }
}

例如,当我使用/ shenburak中的链接进入/ burakshen地址时,它不会被重新渲染

1 个答案:

答案 0 :(得分:0)

我制作了这样的解决方案

  componentDidMount() {
    this.getUserPage()
  }
  componentWillReceiveProps() {
    setTimeout(() => {
      this.getUserPage()
    }, 1)
  }

componentDidMount()在页面打开时呈现 componentWillReceiveProps()重新渲染但没有setTimeout

它不起作用

有更好的方法吗?