reactjs 如何在react redux中从API分派响应数据?

qyzbxkaa  于 2023-02-22  发布在  React
关注(0)|答案(2)|浏览(152)

当用户登录时,我可以获得以下Json数据。
约松

{
    "hubs": [
        "111.com",
        "222.com",
        "333.com",
}

下面的代码部分

console.log(response.data.hubs[0])
  console.log(response.data.hubs[1])
  console.log(response.data.hubs[2])

我可以看到如下URL

"111.com", "222.com", "333.com",

在控制台中。
但是,我使用了dispatch、stores和useSelector,得到了如下错误。

我不知道为什么会出错。
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Login.js

const Login = () => {

  const history = useHistory();
  const dispatch = useDispatch();
  const [cookies, setCookie] = useCookies();
  const { register, handleSubmit, watch, errors } = useForm();

  const getJwt = async (data) =>{

        const email_encoded = btoa(data.email)
        const password_encoded = btoa(data.password)
        await axios.get('xxx.com', {
          auth: {
            username: data.email,
            password: data.password,
          }
          })
        .then(function (response) {
          console.log("logged in!");
          setCookie('accesstoken', response.data.token, { path: '/' }, { httpOnly: true });
          setCookie('refreshtoken', response.data.refresh_token, { path: '/' }, { httpOnly: true });
          console.log(response.data.hubs[0])
          console.log(response.data.hubs[1])
          console.log(response.data.hubs[2])
          dispatch(setMCUHouse(response.data.hubs[0]));
          dispatch(setMCUCondo(response.data.hubs[1]));
          dispatch(setMCUOffice(response.data.hubs[2]));
        })
        .catch(err => {
            console.log("miss");
            alert("Email or Password is wrong!");
        });
      };

  return (
    <>
            <form onSubmit={handleSubmit(getJwt)}>
              <input placeholder='Email Address' className='form-control login_form' {...register('email')} />
              <div className="login_password_section">
                <input placeholder='Password' className='form-control login_form'  />
                <span
                    onClick={togglePassword}
                    role="presentation"
                    className="password_reveal"
                    >
                </span>
              </div>
            </form>

    </>

  );
}
export default Login;

stores/mcu.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  mcuhouse: '',
  mcucondo: '',
  mcuoffice: '',
};

const slice = createSlice({
  name: "mcu",
  initialState,
  reducers: {

    setMCUHouse: (state, action) => {
      return Object.assign({}, state, { mcuhouse: action.payload })
    },
    setMCUCondo: (state, action) => {
      return Object.assign({}, state, { mcucondo: action.payload })
    },
    setMCUOffice: (state, action) => {
      return Object.assign({}, state, { mcuoffice: action.payload })
    },

  }
});

export default slice.reducer;

export const { setMCUHouse, setMCUCondo, setMCUOffice,  } = slice.actions;

DiscoverCondo.js

const url = useSelector(state => state.mcu.mcucondo);
  console.log(url)
r7xajy2e

r7xajy2e1#

根据RTK document
应该这样设置configureStore()

应用程序/商店.js

import { configureStore } from '@reduxjs/toolkit';
import mcuReducer from '...';
export const store = configureStore({
  reducer: {
    mcu: mcuReducer,
  },
});
// ...
eufgjt7s

eufgjt7s2#

我忘记更新stores/index.js
我这样编辑然后通过

商店/索引.js

import { combineReducers } from "redux";
import { configureStore } from "@reduxjs/toolkit";

import mcuReducer from "./mcu";

import { save, load } from "redux-localstorage-simple"

const reducer = combineReducers({
  mcu:mcuReducer
});

const store = configureStore(
  { reducer,
    preloadedState: load(),
    middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(save()), },
  );

export default store;

相关问题