【问题标题】:React router identifier rerender反应路由器标识符重新渲染
【发布时间】:2018-01-05 23:10:00
【问题描述】:

我使用这样的结构:

<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 地址时,它不会重新呈现

【问题讨论】:

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


    【解决方案1】:

    我提出了这样的解决方案

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

    componentDidMount() 在页面打开时渲染 componentWillReceiveProps() 重新渲染,但没有 setTimeout 就无法工作

    有没有更好的办法?

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 2019-04-25
      • 1970-01-01
      • 2021-09-06
      • 2017-02-09
      • 2017-12-23
      • 1970-01-01
      • 2022-07-26
      相关资源
      最近更新 更多