简体   繁体   中英

How to access redux's store state variable in a functional component using useSelector?

I have looked into multiple sources trying to solve this problem but could not find any answers. I have a functional component <Dashboard /> which will display some information from an API.

I expected the component to first get into useEffect, execute the getData function and then display {devices} on the screen. What happens, though, is that the store state is updated, but the component not. The {devices} variable is always undefined. I don't think I understand how to access my state variable from reducers/all/dashboard.js with useSelector.

dashboard/index.js

import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";

import api from "../../services/api";

import * as DashboardActions from "../../store/actions/dashboard";

const Dashboard = (props) => {
  const dispatch = useDispatch();
  const devices = useSelector(state => state.device)

  useEffect(() => {
    async function getData() {
      const pathname = "/dashboard";

      await api
        .get(pathname)
        .then((res) => {
          dispatch(DashboardActions.setData(res.data));
        })
        .catch((res) => {
          console.log(res.response.data);
        });
    }
    getData();
    console.log("devices ue ", devices);

  }, [dispatch]);

  return (
    <div>
      <h1>Dashboard</h1>
      <span>{devices}</span>
    </div>
  );
};

export default Dashboard;

reducers/all/dashboard.js

const INITIAL_STATE = {
  devices: [],
};

function dashboard(state = INITIAL_STATE, action) {
  console.log("Action ", action)
  if ("DASHBOARD_SET_DATA" === action.type) {
    const data = action.data;
    console.log("Data: ", data.devices)
    state = { ...state, devices: data.devices };

    console.log("State ", state)
  }

  return state;
}

export default dashboard;

actions/dashboard.js

export function setData(data) {
  return {
    type: "DASHBOARD_SET_DATA",
    data,
  };
}

I would appreciate any help a lot.

Thanks in advance!

The react-redux useSelector hook is selecting state from your redux store state object.

If your dashboard reducer is combined into your root reducer, something like

const rootReducer = combineReducers({
  ... other reducers
  dashboard,
  ... other reducers
});

Then the devices state value should be accessed from state.dashboard.devices .

The update for your component:

const devices = useSelector(state => state.dashboard.devices)

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