2017-09-05 63 views
0

编辑9/5/17:
事实证明,我在React的反应代码的不同部分存在问题,导致我相信我的堆栈没有正确重置。我在/ Profile页面上渲染的少数几个组件之一是在一个空数组上调用array.length,并且该错误阻止了我的代码运行,并且我的浏览器被冻结。感谢您的期待无论React,Redux使用生命周期方法清除状态

我试图重置组件卸载时在我的商店中的对象的状态(让我们称之为UID)。

UID的初始状态是一个空字符串,当用户点击一个用户名(一个用户发了帖子)我正在渲染一个配置文件组件,但在渲染配置文件组件之前,我正在填充UID,并呈现与UID相匹配的配置文件组件。

我现在想要做的事情是当配置文件组件卸载时清除UID,因此如果用户点击不同的用户名,我可以呈现不同的配置文件。

轮廓组件:

class Profile extends Component { 
    componentWillUnmount() { 
    this.props.clearUserUid() 
    } 
    render() { 
    return (
     <Grid id="profile"> 

     <Grid.Row> 
      <Grid.Column className='profileheader'> 
      <ProfileHeader /> 
      </Grid.Column> 
      </Grid.Row> 

      <Grid.Row> 
      <Grid.Column> 
       <AddSocial/> 
       <ListOfSocialLinks/> 
      </Grid.Column> 
      </Grid.Row> 

     </Grid> 
    ); 
    } 
} 

行动

export const clearUserUid = uid => ({ 
    type: 'CLEAR_UID', payload: '' 
}) 

减速机:

import initialState from './initialState'; 

export default function (userUid = initialState.userUid, action) { 
    switch (action.type) { 
    case 'CLEAR_UID': 
     return action.payload; 
    default: 
     return userUid; 
    } 

}

初始状态

userUid: '', 

组件听userUid

class ListOfSocialLinks extends Component { 
    constructor(props) { 
    super(props); 
    } 

    componentDidMount() { 
    if(this.props.userUid && this.props.userUid.length > 0) { 
     firebase.database().ref(`users/${this.props.userUid}/social`).on('value', snapshot => this.props.fetchSocial(snapshot.val())); 
    } 
    else { 
     firebase.database().ref(`users/${this.props.userData.uid}`).on('value', snapshot => { 
     return this.props.fetchSocial(snapshot.val()) 
     }) 
    } 
    } 


    render() { 
    const { social, userData } = this.props; 
    return (<div className="social"> { this.renderSocial(social, userData) }</div>); 
    } 
} 

userData.uid始终可供用户查看自己的个人资料。

clearUserUid操作运行,并且我的存储状态更改为空字符串,但是当我在配置文件组件卸载后单击其他用户时,页面上出现错误。

如何正确地将商店的状态重置为空字符串?

+0

你试过用'null'而不是空字符串 –

+0

@Amr我刚刚编辑我的文章并添加了正在监听userUid更改的代码。我试图重新调整null作为有效负载,但我无法调用空对象的长度,所以我的组件不会渲染 – Generaldeep

回答

0

它看起来像你的例子中缺少一些代码,但我的猜测是组件本身实际上并没有卸载。当属性通过redux更改时,它不会挂载/卸载,只是重新呈现。

有几个事件可以插入。我的建议是使用componentWillUpdate来查看参数uid已更改并触发清除。

// Invoked whenever there is a prop change 
// Called BEFORE render 
componentWillReceiveProps(nextProps) { 
    // Not called for the initial render 
    // Previous props can be accessed by this.props 
    // Calling setState here does not trigger an an additional re-render 
} 

// Called IMMEDIATELY BEFORE a render 
componentWillUpdate(nextProps, nextState){ 
    // You cannot use this.setState() in this method 
} 

// Called IMMEDIATELY AFTER a render 
componentDidUpdate(prevProps, prevState){ 
} 

如果不是这种情况,您可能需要用更多示例重新处理该问题。

+0

我再次编辑我的帖子反映了这一点。事实证明,国家正在发生变化。我有一个问题,在我的代码中导致错误的地方。感谢关于生命周期方法的建议。为了学习的目的,我会查看它们。 – Generaldeep