简体   繁体   English

React/Redux - 如何在 React 组件中显示 Redux 存储中的值?

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

Just getting started with React / Redux.刚刚开始使用 React / Redux。

I've implemented auth with Firebase, and able to store the logged-in user in Redux store:我已经使用 Firebase 实现了身份验证,并且能够将登录用户存储在 Redux 商店中:

App.js:应用程序.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:我的 Redux 存储在 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. 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?在我的 Header.js 组件中获取“商店”的正确方法是什么?

Since you're using functional components, you can use useSelector :由于您使用的是功能组件,因此可以使用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:对所有类型的组件都可用的另一个选项是使用mapStateToProps function connect

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有关更多信息,请参阅有关 useSelector 的文档: https://react-redux.js.org/api/hooks#useselector

And here's the documentation on connect: https://react-redux.js.org/api/connect这是关于连接的文档: https://react-redux.js.org/api/connect

you can try this as well.你也可以试试这个。 add this part to the Header component将此部分添加到 Header 组件中

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

then add the following code to the index.jsx然后将以下代码添加到 index.jsx

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

I am new to React as well, so I have limited knowledge on it.我也是 React 新手,所以我对它的了解有限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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