代码之家  ›  专栏  ›  技术社区  ›  Samra

如何在减速器中设置State-React

  •  0
  • Samra  · 技术社区  · 3 年前

    我正在学习使用Action、reducers和store。 目标是在单击按钮时将Msg(h1)的值更改为user.email。

    CodeSandbox链接: https://codesandbox.io/s/winter-moon-x4kld?file=/src/index.js

    我应该如何添加setMsg()。。在减速器中?

    以下是代码:

    索引.js

    import { StrictMode } from "react";
    import ReactDOM from "react-dom";
    import { PersistGate } from "redux-persist/lib/integration/react";
    import { persistStore, persistReducer } from "redux-persist";
    import storage from "redux-persist/lib/storage"; // defaults to localStorage for web
    import { createStore } from "redux";
    import { Provider } from "react-redux";
    import { combineReducers } from "redux";
    import isLogged from "/src/isLogged.js";
    
    import App from "./App";
    
    const allReducers = combineReducers({
    user: isLogged
    });
    
    const persistConfig = {
     key: "root",
     storage
    };
    
    const persistedReducer = persistReducer(persistConfig, allReducers);
    const store = createStore(
    persistedReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
    );
    let persistor = persistStore(store);
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(
    <StrictMode>
     <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}>
        <App />
      </PersistGate>
      </Provider>
     </StrictMode>,
     rootElement
    );
    

    应用程序.js

    import "./styles.css";
    import isLoggedUser from "/src/actions/user.js";
    import { useDispatch } from "react-redux";
    import { useState } from "react";
    
    export default function App() {
    const dispatch = useDispatch();
    const [msg, setMsg] = useState("Start editing to see some magic happen!");
    const user = {
    id: 19,
    login: "namrata",
    firstname: "Namrata",
    lastname: "B",
    email: "[email protected]"
    };
    
    const printValues = (e) => {
    e.preventDefault();
    
    dispatch(isLoggedUser(user.email));
    };
    return (
     <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>{msg}</h2>
      <button onClick={printValues}>Load User</button>
    </div>
    );
    }
    

    actions/user.js

    const isLoggedUser = (data) => {
    
    return {
      type:'isLogged', payload: data
    }
    }
    export default isLoggedUser;
    

    isLogged.js

     const initialState = {
     data: 0
    };
    
    const loggedUser = (state = initialState, action) => {
    switch (action.type) {
    case "isLogged":
      return { ...state, data: action.payload };
    default:
      return state;
    }
    };
    
    export default loggedUser;
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Samra    3 年前

    可以所以我的问题的答案可能是使用Selector

    我在App.js中添加了以下内容

    const email = useSelector((state) => state?.user?.data || "abc");
    

    并将消息更改为电子邮件,如下所示

    <h2>{email}</h2>