2016-03-23 16 views
11

の中に派遣し、コンポーネント自体は次のようになります。無限ループIが反応-ルータを(パス=「プロファイル/:ユーザー名」)によってロードされたプロファイルの構成要素を持っているcomponentWillReceiveProps

... 
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アクション

function fetchUser(id) { 
    let token = localStorage.getItem('jwt'); 
    return { 
    [CALL_API]: { 
     endpoint: `http://localhost:3000/api/users/${id}`, 
     method: 'GET', 
     headers: { 'x-access-token': token }, 
     types: [FETCH_USER_REQUEST, FETCH_USER_SUCCESS, FETCH_USER_FAILURE] 
    } 
    } 
} 

私はcomponentWillReceiveProps機能を追加した理由は別のURLの変更時に反応させることである:ユーザ名を、ユーザーが情報をプロファイリングすることをロードするために、この(Reduxの-API-ミドルウェア)のように見えます。一見すると、すべてがうまくいくように見えますが、コンポーネントWillReceiveProps関数が無限ループで呼び出されてデバッグ中に気付きましたが、理由はわかりません。 componentWillReceivePropsを削除すると、プロファイルは新しいユーザー名で更新されませんが、ループに問題はありません。何か案は?

答えて

2

あなたのcomponentWillReceivePropsが無限ループにある理由は、この関数は、Propsが変更され、fetchUserを呼び出すたびに呼び出され、そのためにPropsを変更するアクションが送出されるためです。

特定の小道具の変更は小道具を比較するための条件を追加するhttps://stackoverflow.com/a/36207102/2085190

+1

を比較することができます。 FETCH_USER_SUCCESSの減速器には、私のProfileコンポーネントが接続していたsomユーザデータが格納されています(質問を書くときに上のコードに追加するのを忘れていました)。そのため、flowはcomponentWillReceiveProps - > dispatcher - > reducerによってプロファイルが接続するデータを更新しました - > componentWillReceivePropsが再び呼び出され、すべてが再開されました。私は、このループを避けるために、どこかでルート変更のコードを移動する必要があると思います。ありがとう! – hazmah0

15

てみを見ているかどうかを確認するための比較を追加します。あなたのコンポーネントがそれを必要とする場合。

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

プロファイル/のようないくつかのパスのparamsとルートを反応させている場合:ユーザ名、 あなたは、単に私が今理解props.location.pathname

componentWillReceiveProps(nextProps){  
    if(nextProps.location.pathname !== this.props.location.pathname){ 
      dispatch() 
     } 
} 
関連する問題