【问题标题】:Stateless component using Redux使用 Redux 的无状态组件
【发布时间】:2019-07-24 15:50:07
【问题描述】:

我的问题是,如果我将 redux 与 mapStateToProps 一起使用,我可以从我的父亲组件中获取道具吗?因为我试图将道具从我的父亲组件传递给我的无状态组件,并且只传递了来自 mapStateToPros 的道具。

这是我对组件的调用

case ModalsEnum.ListaTransferenciaDeCasos:
      return (
        <ListaTransferenciasDeCasos
        openModal={(modalCode) =>
          this.props.openModal(modalCode)}
          />
    );

这是我的无状态组件

import * as React from 'react';
import '../../../assets/css/notification.css'
import { connect }  from 'react-redux';
import { ModalsEnum } from '../../../entities/ModalsEnum';

const mapStateToProps = state => {
    return { transfereciasDeCasos: state.TransferenciaDeCasos.transferenciasDeCasos }
}
interface NotificationProps {
    transfereciasDeCasos:any,
    openModal: (modalCode: number) => void;
}
const Notification_ = ( props: NotificationProps ) => {
    const { transfereciasDeCasos, openModal } = props;
        return(
                    <button className="btn btn-default btn-notification" type="button" onClick={() => openModal(ModalsEnum.ListaTransferenciaDeCasos)}>
                        <img className="" src={require("../../../assets/icons/file-icons/svg/ic_notifications_24px.svg")} alt=""/> <span>{transfereciasDeCasos.length}</span>                          
                    </button>
        );
    }

const Notification = connect(mapStateToProps)(Notification_)

export default Notification

【问题讨论】:

    标签: reactjs redux components


    【解决方案1】:

    mapStateToProps 也传递了 ownProps。您可以像这样访问它们:

    const mapStateToProps = (state, ownProps) => {
       return {
         transfereciasDeCasos: state.TransferenciaDeCasos.transferenciasDeCasos,
         ...ownProps
       }
    }
    

    【讨论】:

    • 我认为这种方式只适用于有状态的组件。
    【解决方案2】:

    是的。您传递给子组件的道具将自动成为props 对象的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-09
      • 2020-04-23
      • 1970-01-01
      • 2022-01-14
      • 2021-11-29
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多