Home > Enterprise >  deleting mapStateToProps will give undefined
deleting mapStateToProps will give undefined

Time:10-15

I am React beginner, trying to convert class to hooks, need an advice/help on how to safely remove 'mapStateToProps ' without getting undefined.

i have page A.js and page B.js.

Component B.js i have posted whole code here so it is simple to understand. At the moment console log will give me an array of objects.

If i remove 'mapStateToProps ' and set connect(null, null)(ConnectedList)

then console log will give me 'undefined'.

This is my A.js where i'm using component B.js:

    <React.Fragment>
                <h3>
                  <Trans i18nKey="home.brokers">Brokers</Trans>
                </h3>
                <B action="brokers" actionArgs={site.identifier} />
                <h3>
                  <Trans i18nKey="home.cameras">Cameras</Trans>
                </h3>
                <B action="cameras" actionArgs={site.identifier} />
              </React.Fragment>

this is my B.js which i want to convert and get rid of 'mapStateToProps '

import React, { Component, useEffect, useState } from "react";
import { connect, useDispatch } from "react-redux";
const mapStateToProps = (state) => ({
  sites: state.articles.sites,
  analysers: state.siteArticles.analysers,
  brokers: state.siteArticles.brokers,
  cameras: state.siteArticles.cameras,
  platforms: state.siteArticles.platforms,
});

function ConnectedList(props) {
  console.log("data", props[props.action]);

  return <div></div>;
}

const B= connect(mapStateToProps, null)(ConnectedList);

export default B;

CodePudding user response:

We connect a Component to the Redux when we want to read or change a value.

Otherwise, there is no need for Redux.

Just skip it

export default Component

CodePudding user response:

I suggest that you use useSelector hook from react-redux to solve this problem.

As you can define any logic in your callback in useSelector you can easily extract the part of the state you need from props.action. If you want you can even lift this logic into a separate selector function then add it to your useSelector parameter.

export default function ConnectedList(props) {
  const data = useSelector((state) => {
    const articles = {
      sites: state.articles.sites,
      analysers: state.siteArticles.analysers,
      brokers: state.siteArticles.brokers,
      cameras: state.siteArticles.cameras,
      platforms: state.siteArticles.platforms,
    };

    return articles[props.action];
  });

  return <div></div>;
}
  • Related