Reactjs 在呈现组件React之前从API获取数据,Redux
我在redux商店的初始状态是Reactjs 在呈现组件React之前从API获取数据,Redux,reactjs,redux,react-redux,Reactjs,Redux,React Redux,我在redux商店的初始状态是 const initialState = { token:localStorage.getItem('token'), isAuthenticated: null, isLoading: false, user:null, } 我的应用程序组件看起来像:store.dispatchloadUser;检查本地存储的令牌,如果令牌存在且正确,则从API加载用户 class App extends Component { componentWill
const initialState = {
token:localStorage.getItem('token'),
isAuthenticated: null,
isLoading: false,
user:null,
}
我的应用程序组件看起来像:store.dispatchloadUser;检查本地存储的令牌,如果令牌存在且正确,则从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开发工具显示用户已加载并已验证:true。我的问题是:如何在渲染功能之前加载我的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);
提前谢谢你 即使在isAuthenticated更新为true之前,仍将呈现ArticleList。因此,每次都会发生重定向。这可以通过等待主路由器的渲染直到身份验证完成来解决。
例如:
这将阻止所有路由,直到身份验证检查完成。如果需要启用某些不需要身份验证的路由,请应用条件呈现。我假设Redux存储中的isAuthenticated属性未与localStorage同步?因此,如果重新加载页面,它将采用默认状态下的值,即null
function BaseRouter(props) {
return !props.isLoading ? (
<Router>
<Route />
<Route />
<Route />
</Router>
) : null;
}
const mapStateToProps = state => ({ isLoading: state.authReducer.isLoading });
export default connect(mapStateToProps)(BaseRouter);