【问题标题】:how to replace maptostateprops with useselector within comsposition component如何在组合组件中用 useselector 替换 maptostateprops
【发布时间】:2021-09-14 01:23:33
【问题描述】:

您好,我有一段旧代码,想使用 react-redux 钩子进行转换,有人可以启发一下吗?

const Link = ({
  active,
  children,
  onClick
}) => {
  if (active) {
    return <span>{children}</span>;
  }

  return (
    <a href='#'
       onClick={e => {
         e.preventDefault();
         onClick();
       }}
    >
      {children}
    </a>
  );
};

const mapStateToLinkProps = (
  state,
  ownProps
) => {
  return {
    active:
      ownProps.filter ===
      state.visibilityFilter
  };
};
const mapDispatchToLinkProps = (
  dispatch,
  ownProps
) => {
  return {
    onClick: () => {
      dispatch({
        type: 'SET_VISIBILITY_FILTER',
        filter: ownProps.filter
      });
    }
  };
}
const FilterLink = connect(
  mapStateToLinkProps,
  mapDispatchToLinkProps
)(Link);

const Footer = () => (
  <p>
    Show:
    {' '}
    <FilterLink filter='SHOW_ALL'>
      All
    </FilterLink>
    {', '}
    <FilterLink filter='SHOW_ACTIVE'>
      Active
    </FilterLink>
    {', '}
    <FilterLink filter='SHOW_COMPLETED'>
      Completed
    </FilterLink>
  </p>
);

我知道如何用useselector(state)替换mapstatetoprops(state),但不知道如何替换mapstatetoprops(state,props),这是项目链接:https://embed.plnkr.co/github/eggheadio-projects/getting-started-with-redux/master/29-react-redux-generating-containers-with-connect-from-react-redux-footerlink?show=script,preview

【问题讨论】:

    标签: javascript reactjs redux react-redux react-hooks


    【解决方案1】:

    在使用mapstatetoprops 时添加一个新的prop 过滤器以替换以前的ownprops,如下所示:

    const Link = ({
          active,
          children,
          onClick,
        + filter
        }) => {
        +const active = useSelector(state => state.visibilityFilter == filter)
    

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 2011-07-18
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2022-12-09
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多