Как я могу добавить Redux в приложение React с аутентификацией? - PullRequest
0 голосов
/ 24 марта 2020

Я добавил поддержку MSAL в свое приложение React. Но теперь я хочу добавить Redux для управления состоянием. Кажется, мне нужно обернуть приложение как компонентом AuthProvider, так и компонентом Redux Provider. Я не знаком с синтаксисом того, как AuthProvider определяет экспорт по умолчанию. Поэтому, когда я пытаюсь вызвать commbine, AuthProvider, кажется, не определен так, чтобы объединение могло получить к нему доступ. Как мне структурировать мой код, чтобы я мог выполнить sh оба?

Ниже приведен мой текущий код с некоторыми подробностями, удаленными для краткости.

Индекс. js

ReactDOM.render(
  <React.StrictMode>
      <App />
  </React.StrictMode>,
  document.getElementById('root')
);

Приложение. js

import AuthProvider from "./AuthProvider";

function App(props) {
  return (
    <div className="App">
      <React.Fragment>
        <Router>
          <NavigationMenu
            isAuthenticated={props.isAuthenticated}
            authButtonMethod={props.isAuthenticated ? props.onSignOut.bind(this) : props.onSignIn.bind(this)}
            user={props.account} />
          <Container>
            <Switch>
              <Route exact path="/" isAuthenticated={props.isAuthenticated} render={(props) => <Home {...props} isAuthenticated={props.isAuthenticated} />} />
              <ProtectedRoute path="/configuration" component={Configuration} isAuthenticated={props.isAuthenticated}></ProtectedRoute>
              <ProtectedRoute path="/otherComponent" component={OtherComponent} isAuthenticated={props.isAuthenticated}></ProtectedRoute>
            </Switch>
          </Container>
        </Router>
      </React.Fragment>
    </div>
  );
}

export default AuthProvider(App);

AuthProvider. js

export default AuthComponent =>
    class AuthProvider extends Component {
        // lots of code skipped here
        render() {
            return (
                <Provider store={store}>
                    <AuthComponent
                        {...this.props}
                        account={this.props.account}
                        isAuthenticated={this.props.isAuthenticated}
                        error={this.props.error}
                        graphProfile={this.props.graphProfile}
                        onSignIn={() => this.onSignIn(useRedirectFlow)}
                        onSignOut={() => this.onSignOut()}
                    />
                </Provider>
            );
        }
    };

const mapStateToProps = (state) => {
    return {
        auth: state.authReducer
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        setError: (error) => {
            dispatch(setError(error));
        },
        setAuth: (account) => {
            dispatch(setAuth(account));
        },
        setGraphProfile: (graphProfile) => {
            dispatch(setGraphProfile(graphProfile));
        }
    }
};

connect(mapStateToProps, mapDispatchToProps)(AuthProvider); // <-- This is the line that breaks

1 Ответ

1 голос
/ 24 марта 2020

Это совсем не то, как вы настраиваете аутентификацию в проекте React. Используйте https://reactjs.org/docs/create-a-new-react-app.html#create -react-app , чтобы увидеть, как структурирован проект React. Попробуйте это:

class AuthProvider extends Component {
    // lots of code skipped here
    render() {
        return (
                <AuthComponent
                    {...this.props}
                    account={this.props.account}
                    isAuthenticated={this.props.isAuthenticated}
                    error={this.props.error}
                    graphProfile={this.props.graphProfile}
                    onSignIn={() => this.onSignIn(useRedirectFlow)}
                    onSignOut={() => this.onSignOut()}
                />
        );
    }
};
const mapStateToProps = (state) => {
return {
    auth: state.authReducer
}
};

const mapDispatchToProps = (dispatch) => {
return {
    setError: (error) => {
        dispatch(setError(error));
    },
    setAuth: (account) => {
        dispatch(setAuth(account));
    },
    setGraphProfile: (graphProfile) => {
        dispatch(setGraphProfile(graphProfile));
    }
}
};

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

Поставщик store = {store} должен обернуть ваш root компонент, а не AuthProvider. Прочтите это https://reacttraining.com/react-router/web/guides/quick-start и документацию Redux.

...