小编haz*_*ah0的帖子

在componentWillReceiveProps中调度时的无限循环

我有一个由react-router(path ="profile /:username")加载的Profile组件,组件本身如下所示:

...
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);
Run Code Online (Sandbox Code Playgroud)

而fetchUser动作看起来像这样(redux-api-middleware):

function fetchUser(id) {
  let token = localStorage.getItem('jwt');
  return {
    [CALL_API]: {
      endpoint: `http://localhost:3000/api/users/${id}`, …
Run Code Online (Sandbox Code Playgroud)

reactjs react-router redux react-redux react-router-redux

13
推荐指数
3
解决办法
1万
查看次数