首页 > 解决方案 > Reactjs-Redux:即使在用户登录后,mapStateToProps 也会返回 user is authenticated as first,然后是 true

问题描述

我已经用 reactjs 实现了 redux,我所有的身份验证都到位了。

因此,每当用户进行身份验证时,都会在 redux 存储中存储一个令牌,

我已经使用我的应用程序组件实现了 mapStateToProps 函数,如果令牌可用,则将 prop isAuthenticated 映射为 true。

我还实现了 mapDispatchToProps 函数来调度一个检查用户身份验证状态的动作,这个动作是在 componentDidMount 上调度的。

问题是即使在用户通过身份验证后,prop 'isAuthenticated' 最初返回 false 然后返回 true。

这是代码:

class App extends Component {

  componentDidMount() {
    this.props.getAuthStatus();
  }

  render() {
    //console.log(this.props);

    return (
    <BrowserRouter>
      <div className="App">
        <Navbar {...this.props} />
        <Switch>
          <Route path="/login" component={ LoginForm } />
          <Route path="/register" component={ RegistrationForm } />
        </Switch>
      </div>
    </BrowserRouter>
    );
  }
}


const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.token !== null,
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    getAuthStatus: () => { dispatch(actions.checkAuthStatus()) },
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

动作代码

export const authSuccess = (token) => {
    return {
        type: 'AUTH_SUCCESS',
        token: token
    }
}

export const logout = () => {
    localStorage.removeItem('token');
    return {
        type: 'AUTH_LOGOUT'
    }
}


export const checkAuthStatus = () => {
    return (dispatch) => {
        const token = localStorage.getItem('token');
        if (token === undefined) {
            dispatch(logout());
        } else {           
                dispatch(authSuccess(token));         
        }
}

减速器代码:

const initialState = {
    token: null,
    error: null,
    loading: false
}

export const authSuccess = (state, action) => {
    return updateObject(state, {
        token: action.token,
        error: null,
        loading: false
    })
}

export const authLogout = (state, action) => {
    return updateObject(state, {
        token: null,
    })    
}

const rootReducer = (state=initialState, action) => {
    switch (action.type){
        case 'AUTH_SUCCESS': return authReducers.authSuccess(state, action);
        case 'AUTH_LOGOUT': return authReducers.authLogout(state, action);
        default:
            return state;
    }
}

索引文件:

const storeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const store = createStore(rootReducer, storeEnhancer(
    applyMiddleware(thunk)
));

const app = (
    <Provider store={ store }>
        <App />
    </Provider>
)

ReactDOM.render(app, document.getElementById('root'))

标签: javascriptreactjsredux

解决方案


除非您在初始状态中包含令牌,否则您将看到令牌为 false,直到触发 checkAuthStatus,在您的情况下为 componentDidMount。您可以在初始状态下将 token 设置为 localStorage 值。


推荐阅读