我在redux商店的初始状态是
const initialState = {
token:localStorage.getItem('token'),
isAuthenticated: null,
isLoading: false,
user:null,
}
我的app组件看起来像:store.dispatch(loadUser());如果令牌存在且正确,请检查本地存储的令牌并从API加载用户。
class App extends Component {
componentWillMount() {
store.dispatch(loadUser());
}
render() {
return (
<div className="App">
<Provider store={store}>
<Router>
<BaseRouter/>
</Router>
</Provider>
</div>
);
}
}
export default App;
一切正常,但是当我在浏览器中重新加载组件时,它立即将我重定向到组件,尽管redux dev工具显示用户已加载并且isAuthenticated:true。我的问题是:如何在render()函数之前加载我的redux存储? ?还是有其他想法让它正常工作?
class ArticleList extends Component{
static propTypes = {
articles: PropTypes.array.isRequired,
getArticles: PropTypes.func.isRequired,
}
componentWillMount(){
this.props.getArticles();
}
render(){
console.log('is_auth',this.props.isAuthenticated);// console shows NULL
if (!this.props.isAuthenticated) {
return <Redirect to="/login" />;
}
return(
<Fragment>
<Articles data={this.props.articles}/>
</Fragment>
)
}
}
const mapStateToProps = state =>({
articles: state.articleReducer.articles,
isAuthenticated: state.authReducer.isAuthenticated
})
export default connect(mapStateToProps,{getArticles})(ArticleList);
先感谢您!
甚至在ArticleList
更新为真之前,isAuthenticated
正在呈现。因此,重定向每次都在发生。这可以通过等待主路由器的渲染来解决,直到验证完成。例如:
function BaseRouter(props) {
return !props.isLoading ? (
<Router>
<Route />
<Route />
<Route />
</Router>
) : null;
}
const mapStateToProps = state => ({ isLoading: state.authReducer.isLoading });
export default connect(mapStateToProps)(BaseRouter);
这将阻止所有路由,直到身份验证检查完成。如果需要启用一些不需要身份验证的路由,请应用条件渲染。