Reactjs 在componentWillReceiveProps中分派时的无限循环

Reactjs 在componentWillReceiveProps中分派时的无限循环,reactjs,react-router,redux,react-redux,react-router-redux,Reactjs,React Router,Redux,React Redux,React Router Redux,我有一个配置文件组件,由react router(path=“Profile/:username”)加载,该组件本身如下所示: ... import { fetchUser } from '../actions/user'; class Profile extends Component { constructor(props) { super(props); } componentDidMount() { const { username } = this.pro

我有一个配置文件组件,由react router(path=“Profile/:username”)加载,该组件本身如下所示:

...
import { fetchUser } from '../actions/user';

class Profile extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    const { username } = this.props;
    this.fetchUser(username);
  }
  componentWillReceiveProps(nextProps) {
    const { username } = nextProps.params;
    this.fetchUser(username);
  }
  fetchUser(username) {
    const { dispatch } = this.props;
    dispatch(fetchUser(username));
  }
  render() {...}
}

export default connect((state, ownProps) => {
  return {
    username: ownProps.params.username,
    isAuthenticated: state.auth.isAuthenticated
  };
})(Profile);
fetchUser操作如下所示(redux api中间件):


我之所以添加componentWillReceiveProps函数,是为了在URL更改为另一个用户名时做出反应,并加载该用户的配置文件信息。乍一看,一切似乎都正常,但我在调试时注意到componentWillReceiveProps函数是在无限循环中调用的,我不知道为什么。如果我删除了componentWillReceiveProps,那么配置文件不会用新用户名更新,但是我没有任何问题。有什么想法吗?

您的
组件将接收道具
处于无限循环中,因为调用
fetchUser
将发送一个更新道具的操作

添加一个比较,以在分派操作之前检查特定道具是否更改。 编辑:

React 16.3+
中,组件将收到道具
将被缓慢弃用

建议使用
componentdiddupdate
代替
componentWillReceiveProps


请参见

尝试添加条件以比较道具。如果您的组件需要它

componentWillRecieveProps(nextProps){
 if(nextProps.value !== this.props.value)
  dispatch(action()) //do dispatch here 
}

如果您有带有一些路径参数(如profile/:username)的react路由, 您只需比较props.location.pathname

componentWillReceiveProps(nextProps){    
    if(nextProps.location.pathname !== this.props.location.pathname){
          dispatch()
        }
 }  

我现在明白了。FETCH_USER_SUCCESS的reducer存储了som用户数据,我的概要文件组件正在通过该数据进行连接(在编写问题时,我忘记将其添加到上面的代码中)。因此,流程为componentWillReceiveProps-->dispatcher-->reducer更新配置文件在-->componentWillReceiveProps上连接的数据,并再次调用该流程,然后重新开始。我想我需要将路由更改的代码移到其他地方以避免这种循环。谢谢
componentWillRecieveProps(nextProps){
 if(nextProps.value !== this.props.value)
  dispatch(action()) //do dispatch here 
}
componentWillReceiveProps(nextProps){    
    if(nextProps.location.pathname !== this.props.location.pathname){
          dispatch()
        }
 }