简体   繁体   中英

React/Redux - How to display a value from Redux store in React component?

Just getting started with React / Redux.

I've implemented auth with Firebase, and able to store the logged-in user in Redux store:

App.js:

import React, { useEffect } from "react";
import { Switch, Route } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import Login from "./pages/auth/Login";
import Register from "./pages/auth/Register";
import Home from "./pages/Home";
import Header from "./components/nav/Header";
import RegisterComplete from "./pages/auth/RegisterComplete";

import { auth } from "./firebase";
import { useDispatch } from "react-redux";

const App = () => {
  const dispatch = useDispatch();

  // to check firebase auth state
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(async (user) => {
      if (user) {
        const idTokenResult = await user.getIdTokenResult();
        console.log("user", user);
        dispatch({
          type: "LOGGED_IN_USER",
          payload: {
            email: user.email,
            token: idTokenResult.token,
          },
        });
      }
    });
    // cleanup
    return () => unsubscribe();
  }, [dispatch]);

  return (
    <>
      <Header />
      <ToastContainer />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route exact path="/login" component={Login} />
        <Route exact path="/register" component={Register} />
        <Route exact path="/register/complete" component={RegisterComplete} />
      </Switch>
    </>
  );
};

export default App;

My Redux store is defined in Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { BrowserRouter} from "react-router-dom";
import 'antd/dist/antd.css';
import { createStore } from "redux";
import { Provider } from "react-redux";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "./reducers";

const store = createStore(rootReducer, composeWithDevTools());

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
);

In my Header component I want to display the email of the logged-in user, which is being stored in Redux store like "store.user.email", which I can clearly see in the Redux console tab in the browser.

What is the proper way of getting a hold of 'store' in my Header.js component?

Since you're using functional components, you can use useSelector :

import { useSelector } from 'react-redux';

const Header = () => {
  const email = useSelector(store => store.user.email);

   // do whatever with the email
};

The other option, which is available to all types of components, is to use connect with a mapStateToProps function:

import { connect } from 'react-redux';

const Header = ({ email }) => {
  // do whatever with the email prop
};

const mapStateToProps = (store) => ({
  email: store.user.email
});

export default connect(mapStateToProps)(Header);

For more information, here's the documentation on useSelector: https://react-redux.js.org/api/hooks#useselector

And here's the documentation on connect: https://react-redux.js.org/api/connect

you can try this as well. add this part to the Header component

 componentDidMount() { 
        store.subscribe(() => { 
            this.setState({})
        })
    }

then add the following code to the index.jsx

store.subscribe(()=> { 
ReactDOM.render(
 <App />,
 document.getElementById('root')
)
})

I am new to React as well, so I have limited knowledge on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM