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



刚刚开始使用React/Redux。

我已经用Firebase实现了身份验证,并且能够将登录的用户存储在Redux存储中:

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;

我的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')
);

在我的Header组件中,我想显示登录用户的电子邮件,该电子邮件存储在Redux商店中,如";store.user.email";,我可以在浏览器的Redux控制台选项卡中清楚地看到。

在我的Header.js组件中获取"store"的正确方法是什么?

由于您使用的是功能组件,因此可以使用useSelector:

import { useSelector } from 'react-redux';
const Header = () => {
const email = useSelector(store => store.user.email);
// do whatever with the email
};

所有类型的组件都可以使用的另一个选项是使用带有mapStateToProps功能的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);

有关更多信息,请参阅useSelector的文档:https://react-redux.js.org/api/hooks#useselector

以下是有关connect的文档:https://react-redux.js.org/api/connect

您也可以尝试一下。将该部分添加到标题组件

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

然后将以下代码添加到index.jsx

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

我也是React的新手,所以我对它的了解有限

相关内容

  • 没有找到相关文章

最新更新