编辑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操作运行,并且我的存储状态更改为空字符串,但是当我在配置文件组件卸载后单击其他用户时,页面上出现错误。
如何正确地将商店的状态重置为空字符串?
你试过用'null'而不是空字符串 –
@Amr我刚刚编辑我的文章并添加了正在监听userUid更改的代码。我试图重新调整null作为有效负载,但我无法调用空对象的长度,所以我的组件不会渲染 – Generaldeep