从 React 容器获取 props 到功能组件

Get props from React container to functional component

这是我的容器的样子:

class Shipping extends React.PureComponent {
   constructor(props) {
       super(props)
   }
   componentDidUpdate(prevProps) {
       if (prevProps.match.params.shippingId !== this.props.match.params.shippingId) {
        
           this.props.getShippingDetails(this.props.match.params.shippingId)
       }
   }
   render = () => this.props.isLoading ? null : <ShippingView removeOrder={this.props.removeOrder} />
}
const mapStateToProps = ({ shippingDetails}) => ({
    isLoading: shippingDetails.isLoading
})

const mapDispatchToProps = (dispatch) => ({
    getShippingDetails: (id) => dispatch(shippingActions.getShippingDetails(id)),
    removeOrder: (id) => dispatch(shippingActions.removeOrder(id))
})

export default () => Shared.accessPageWrapper([["acess:all"], ["admin:control", "navigation/shopping:view"]], (connect(mapStateToProps, mapDispatchToProps)(Shipping)), <Shared.AccessDeniedView  />)

这是我的功能组件的样子:

export const accessPageWrapper = (
    permissionsAllowed = [],
    component = null,
    accessDeniedView,
    accessDenied = true
) => {
    const permissions = useSelector(state => state.user.permissions)
    const permitted = permissionsAllowed.some((permission) => permission.every(el => permissions.includes(el)), false)
    if (permitted) {
        const Component = component
        return <Component />
    }
    return accessDenied ? accessDeniedView : null
}

我无法通过功能组件传递道具,如下所示:

const Component = component
return <Component {...props} />

由于这个问题,我收到以下错误,因为我的道具婴儿车未定义。

Uncaught TypeError: Cannot read property 'params' of undefined

我不知道如何解决这个问题:/你能帮帮我吗? 另外,我不想将上述功能组件更改为 class 组件。 有什么办法可以检索组件的道具吗?提前致谢!!

我认为您只是缺少组件的 return。高阶组件使用一个组件(和其他可能的参数)和 return 一个新的装饰组件。

export const accessPageWrapper = (
  permissionsAllowed = [],
  component = null,
  accessDeniedView,
  accessDenied = true
) => (props) => { // <-- return a functional component
  const permissions = useSelector((state) => state.user.permissions);
  const permitted = permissionsAllowed.some(
    (permission) => permission.every((el) => permissions.includes(el)),
    false
  );
  if (component && permitted) { // <-- Ensure component exists!
    const Component = component;
    return <Component {...props} />; // <-- spread passed props to Component
  }
  return accessDenied ? accessDeniedView : null;
};

可能需要更新导出。

import { accessPageWrapper } from '.....';

...

export default accessPageWrapper(
  [["acess:all"], ["admin:control", "navigation/shopping:view"]], 
  connect(mapStateToProps, mapDispatchToProps)(Shipping), 
  <Shared.AccessDeniedView />,
);