【问题标题】:componentWillReceiveProps not firing on router param changecomponentWillReceiveProps 未在路由器参数更改时触发
【发布时间】:2016-09-06 04:59:23
【问题描述】:

我正在使用 react-router-redux 以及 reduxreact-routerreact,并且在这个 repo 中一切正常:

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

(查看分支issue-branch 以复制我的问题)

我已经使用react-router-reduxreact-router 状态集成到我的redux 状态中,并且可以成功地使用mapStateToProps 从props 中获取我需要的路由器参数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(TheemployeeId 是 ${this.props.employeeId}),它会随着我路由到该组件和参数的变化而变化。

但由于我不明白的原因,当参数更改时这不会触发。

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

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

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

我是不是搞错了?

【问题讨论】:

    标签: reactjs redux redux-router


    【解决方案1】:

    componentWillReceiveProps 仅在道具更改时触发。在您的情况下,您的初始道具设置为 employeeId 并且不会更改。您可以通过componentWillMount 联系employeeId

    而您的selectEmployee call 的问题在于它不会调度employeeSelected,因为hasLoadedEMPLOYEE_RECEIVED 操作中被设置为true 一次并且以后永远不会改变,所以selectEmployee 在调度之前返回employeeSelected,假设在EMPLOYEE_SELECTED 中将hasLoaded 改回false。

    【讨论】:

    • 你是对的,我最终发现,由于路线正在改变,它正在重新安装......白痴。您的解决方案是正确的。
    猜你喜欢
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 2018-08-16
    • 2018-07-07
    • 1970-01-01
    • 2018-04-08
    相关资源
    最近更新 更多