componentWillReceiveProps未在路由器参数更改

时间:2016-09-06 04:59:23

标签: reactjs redux redux-router

我正在使用react-router-redux以及reduxreact-routerreact,并且在此回购协议中一切运作良好:

https://github.com/justsayno/redux-react-introduction-code/tree/issue-branch

(查看分支issue-branch以重现我的问题)

我已使用react-routerreact-router-redux状态集成到我的redux状态,并且可以成功使用mapStateToProps从道具中获取我需要的路由器参数employeeId,如下所示:

(以下内容来自this file

const mapStateToProps = (state, ownProps) => ({ 
    employeeId : ownProps.params.employeeId,
    employee: state.selectedEmployee.item,
    hasLoaded: state.selectedEmployee.hasLoaded,
    hasError: state.selectedEmployee.hasError,
    error: state.selectedEmployee.error
})

在我的渲染函数中我可以console.log( employeeId是$ {this.props.employeeId} )并且当我路由到该组件并且参数更改时它会发生变化。

但是由于原因我不明白,当params改变时,这不会触发。

componentWillReceiveProps(nextProps){
    console.log(nextProps)
}

我想要实现的是对员工列表与单个员工的不同模拟API调用,我需要在employeeId参数更改时重新检索员工,否则我只会看到其中一个员工。我打算在componentWillReceiveProps函数中执行此操作,检查employeeId是否有更改,如果有这样的话,请启动操作:

componentWillReceiveProps(nextProps){
    const { employeeId, selectEmployee } = this.props
    if(nextProps.employeeId !== employeeId){
        selectEmployee(nextProps.employeeId)
    }
}

我只是接近这个错误吗?

1 个答案:

答案 0 :(得分:2)

仅当道具发生变化时,

componentWillReceiveProps才会触发。在你的情况下,你有employeeId设置的初始道具,并且不会改变。您可以在employeeId中找到componentWillMount

selectEmployee call的问题在于它不会发送employeeSelected,因为hasLoadedtrue行动中设置为EMPLOYEE_RECEIVED一次,之后永远不会更改,因此selectEmployee会在发送employeeSelected之前返回,hasLoaded会在EMPLOYEE_SELECTED中将type AppLock struct { lockCh chan struct{} unlockCh chan struct{} } func NewAppLock() *AppLock { l := new(AppLock) l.lockCh = make(chan struct{}) l.unlockCh = make(chan struct{}) go l.lockRoutine() return l } func (l *AppLock) lockRoutine() { for { // take the next client off the channel <- l.lockCh // we are now in a locked state; wait until the client has released // which it signals via the channel c <- l.unlockCh } } func (l *AppLock) Lock() { // join the queue for a lock l.lockCh <- struct{}{} } func (l *AppLock) Unlock() { l.unlockCh <- struct{}{} } 更改回false。