编辑 9/5/17:
事实证明,我在 React 中的反应代码的不同部分存在问题,这让我相信我的堆栈没有正确重置。我在 /Profile 页面上渲染的少数组件之一是在一个空数组上调用 array.length,该错误阻止了我的代码运行并且我的浏览器冻结了。感谢您的关注
当组件卸载时,我试图在我的商店中重置对象的状态(我们称之为 UID)。
UID 的初始状态是一个空字符串,当用户单击用户名(发布帖子的用户)时,我正在渲染一个配置文件组件,但在呈现配置文件组件之前,我正在填充 UID,并呈现一个配置文件与 UID 匹配的组件。
我现在想做的是在 Profile 组件卸载时清除 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 操作运行,我的商店状态更改为空字符串,但是,当我在配置文件组件卸载后单击其他用户时,页面上出现错误。
如何正确地将商店的状态重置为空字符串?