【问题标题】:React-Redux: How to update props of component whenever they change?React-Redux:如何在组件更改时更新组件的道具?
【发布时间】:2020-08-18 23:45:48
【问题描述】:

在我手动重新渲染整个页面之前,我的标题组件没有收到新的道具。我想知道为什么?

基本上我有四个条件来呈现我的标题:空闲、加载、成功、失败。

  1. 在空闲时,用户会看到 LoggedOutNavbar
  2. 在加载时,用户会看到 LoadingNavbar
  3. 成功后,用户会看到 LoadedNavbar
  4. 失败时,用户会看到 LoggedOutNavbar

用户第一次访问登录页面时,状态为idle。如果他然后点击登录按钮,则登录成功,但标头没有收到新的加载和成功状态作为道具。因此,标头保持与注销状态相同。但是,当手动重新加载页面并再次分派操作时,新的道具可用并显示新的标题。我想知道如何在不手动重新加载页面的情况下获得相同的结果?

export class Header extends Component {

   componentDidMount() {
    this.props.getProfile();
    this.props.loadUser();
  }
    
    render() {

        const {profile} = this.props.profile;
        const isFetching = this.props.isFetching
        const {isAuthenticated} = this.props.auth

        if (isFetching === "idle") return (<LoggedOutNavbar />)

        if (isFetching === "loading" ) return (<Fragment> <LoadingNavbar /> </Fragment> )

        if (isFetching === "success") return (<LoadedNavbar profile = {profile[0]} isAuthenticated ={isAuthenticated}/>)

        if (isFetching === "failure") return (<LoggedOutNavbar />)


  
}
}


function mapStateToProps(state, ownProps) {
    const auth = state.auth
    const profile = state.profile
    const isFetching = state.profile.isFetching

  return { auth, profile, isFetching}
};

export default connect(
    mapStateToProps,
    { getProfile, loadUser }
)(Header);
header.js:34 idle    // Logged Out state
header.js:34 loading  
header.js:34 success  // Logged in state, after manually rerendering
header.js:34 success // Logged in state, after manually rerendering
header.js:34 idle  // Logged Out state
header.js:34 idle  // Logged in state but header is still in idle
header.js:34 idle  // Logged in state but header is still in idle

编辑: 在检查我的 Redux 开发工具时,我发现配置文件实际上并没有从空闲状态变为另一个状态。我认为登录后不会再次调用 getProfile 函数。

【问题讨论】:

  • 你能通过在 Redux devtools 中查看 state 来确认 state 已经改变了吗?
  • @Wezelkrozum 你是对的。在 Redux-Devtool 中显示的状态没有变化。它保持空闲状态。我想这是因为 ComponentDidMount 中的函数 getprofile 在组件加载时仅调用一次,但在登录后不会调用第二次。
  • @dan_boy 使用 effect 使 Header 成为功能组件可能更简单。如果您看到文档的类示例,那么您会看到您还需要实现 componentDidUpdate 以查看是否某些道具发生了变化。您还可以在登录时设置所需的 redux 状态值,然后 mapStateToProps 应该加载更改的值(除非您在 reducer 中改变状态)。

标签: reactjs redux react-redux


【解决方案1】:

如 cmets 中所述,componentDidMount 在组件最初呈现之前仅被调用一次。但是,要注册组件中的更改,需要componentDidUpdate。每当用户更改isAuthenticated 的状态时,组件都会调用getProfile 操作并再次呈现组件。

componentDidUpdate(prevProps) {
// Update profile after user loggs out or loggs in:
if (this.props.isAuthenticated !== prevProps.isAuthenticated) {
  this.props.getProfile();
}
}

【讨论】:

    猜你喜欢
    • 2018-10-28
    • 2019-09-16
    • 2020-01-16
    • 1970-01-01
    • 2019-03-03
    • 2021-07-13
    • 1970-01-01
    • 2020-08-10
    • 2020-10-22
    相关资源
    最近更新 更多