【问题标题】:How to namespace parent props using mapState如何使用 mapState 命名父道具
【发布时间】:2020-03-08 06:11:45
【问题描述】:

有人告诉我,父组件的 props 会自动传递给子组件,即使您使用以下组件,您也无法拦截它们:

function mapStateToProps(state: RootState,  ownProps: OwnProps) {
  return {
    s: {...state},
    o: {...ownProps},
  };
}

我想确保 state 中的 props 不会与父组件中的 props 发生冲突。有没有

我们正在使用 Redux 连接,例如:

export default connect<StateProps, DispatchProps, AllProps, RootState>(
  mapState,
  mapDispatch
)(OurComponent);

例如,如果我有一个组件

'use strict';

import React from 'react';
import { AppDispatch } from '../../cp';
import { RootState } from '../../reducers/root';
import { connect } from 'react-redux';
import moment from "moment";

interface OwnProps {
  //The type for the props provided by the parent component
  s?: any;
  z1?: any,
  z2?: any,
  z3?: any,
  o?:any

}

function mapDispatch(dispatch: AppDispatch<any>) {
  return { dispatch };
}

function mapState(state: RootState, ownProps: OwnProps) {
  return {
    o: {
      ...ownProps
    },
    s: {
      ...state
    }
  };
}

type StateProps = ReturnType<typeof mapState>;
type DispatchProps = ReturnType<typeof mapDispatch>;
type AllProps = StateProps & DispatchProps & OwnProps;

class Home extends React.Component<AllProps, RootState>{
  constructor(p: AllProps) {
    super(p);
    console.log('home props:', p);
  }

  render(){
    return <div>Home Works</div>;
  }
}


export default connect<StateProps, DispatchProps, AllProps, RootState>(mapState, mapDispatch)(Home);

然后我渲染它:

  <Home dispatch={null as any} s={null as any} o={null as any} z1={1} z2={2} z3={true}/>

我得到了这个记录:

【问题讨论】:

  • 不,这不是真的,我在本周早些时候问过这个问题 - 我的问题也发布在这里:github.com/reduxjs/react-redux/issues/1540
  • 你不需要 connect 原生的 props 和 redux 的 props,只需在你的组件中使用它就足够了。只是不明白为什么要这样做。如果你想要一个清晰的代码视图,我想我已经给你一个解决方案了。
  • 我会投赞成票,让我们听听别人的意见。
  • 我不明白这是什么意思。命名空间存储值足以防止冲突

标签: reactjs redux


【解决方案1】:

我认为唯一好的解决方案是像这样使用mergeProps

interface OwnProps {
  //The type for the props provided by the parent component
}

function mergeProps(state: RootState, dispatch: Dispatch<any>, ownProps: OwnProps) {
  return {
    dispatch,
    o: ownProps,                   // ownProps are namespaced onto o.
    s: {                           // stateProps are namespaced onto s.
      apiInReach: state.dev.apiInReach,
    }
  };
}

 //// ...

export default connect(
  null,
  null,
  mergeProps
)(Dev);

mergeProps 的文档在这里: https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#mergeprops-stateprops-dispatchprops-ownprops--object

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2018-01-17
    • 2020-10-05
    • 2019-06-23
    • 1970-01-01
    • 2020-11-17
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多