2016-08-11 8 views
1

私の主なコンポーネントをロードする必要があり、対地価値が "logged:true"のlocalstorageが存在する場合、react-routerを使用して "/ app"にリダイレクトされます。私が反応し、Reduxの使用していますが、これは私のコードであるcomponentDillMountのcomponentWillMountのRedux状態の変更が認識されませんか?

class Main extends Component { 

    componentWillMount(){ 
// Return true in redux state if localstorage is found 
     this.props.checkLogStatus(); 
    } 

    componentDidMount(){ 
// redirect in case redux state returns logged = true 
     if(this.props.logStatus.logged){ 
      hashHistory.push('/app'); 
     } 
    } 

    render() { 
    return (
    <App centered={true} className="_main"> 
     {this.props.children} 
    </App> 
    ); 
    } 
} 

マイReduxのアクション:

checkLogStatus() { 
    // check if user is logged and set it to state 
    return { 
     type: LOGIN_STATUS, 
     payload: window.localStorage.sugarlockLogged === "true" 
    }; 
} 

しかし、コンポーネントがcomponentDidMount段階になったとき、私のReduxの状態はまだありません更新されました。

componentWillReceiveProps(nextProps){ 
     if (nextProps.logStatus.logged && nextProps.logStatus.logged !== this.props.logStatus.logged){ 
      hashHistory.push('/app'); 
     } 
    } 

しかし、私はそれが最もエレガントな解決策であることを確認していない:

Yは、使用して動作するようにこれを取得するために管理します。

ありがとうございます!

答えて

0

を使用すると、logStatusオブジェクトが変更されている小道具として渡されているので、ここに行く方法はcomponentWillReceivePropsです。

あなたの代わりに、オブジェクトのアクションの引数としてdispatchを受け取る機能を(派遣することを可能にするRedux-thunk middlewareを使用して、このよりエレガントな方法があります。それから、約束にその機能をラップしcomponentWillMountでそれを使用することができます。あなたの行動で

ファイル:

updateReduxStore(data) { 
    return { 
     type: LOGIN_STATUS, 
     payload: data.logInCheck 
    }; 
} 

validateLocalStorage() { 
    ... 
} 

checkLogStatus() { 
    return function(dispatch) { 
     return new Promise((resolve, reject) => { 
      validateLocalStorage().then((data) => { 
       if (JSON.parse(data).length > 0) { 
        dispatch(updateReduxStore(data)); 
        resolve('valid login'); 
       } else { 
        reject('invalid login'); 
       } 
      }); 
     }); 
    }; 
} 

を次に、あなたのコンポーネントで:

componentWillMount() { 
    this.props.checkLogStatus() 
     .then((message) => { 
      console.log(message); //valid login 
      hashHistory.push('/app'); 
     }) 
     .catch((err) => { 
      console.log(err); //invalid login 
     }); 
} 

Redux-thunkミドルウェアは、そのような使用例のために作られています。

関連する問題