0

编辑 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 操作运行,我的商店状态更改为空字符串,但是,当我在配置文件组件卸载后单击其他用户时,页面上出现错误。

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

4

1 回答 1

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){
}

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

于 2017-09-05T01:08:01.327 回答