首页 文章

我应该在哪里发送我的redux

提问于
浏览
1

我正在学习反应和redux,我只是有一个小问题,我应该在哪里发送和共享我的redux商店以反应组件,我应该分享和派遣我的商店在任何需要商店的组件或我应该分享和派遣我的商店在一个主要组件中并将该值作为道具分享订购组件?例如,我有这三个组件,我将状态存储在一个FlashCard组件中,并使用props将该状态共享给Cardlist组件,然后CardList组件将该组件发送到Card组件 . 这是正确的做法吗?而且在卡组件中我使用dispatch因为它看起来更方便,但是我是否应该在我的主要组件FlashCard中使用dispatch并将更改传递给Card组件?谢谢你的帮助 .

import React from 'react';
import CardList from './cardList';
import {connect} from 'react-redux';

const FlashCard =(props)=>{
    return (
    <div>
        <CardList
            cards={props.cards}
        />
    </div>
)}

const mapStateToProps=(state)=>({
    cards:state.cards
})

export default connect(mapStateToProps,null)(FlashCard)

import React from 'react';
import Card from './card';

const CardList =(props)=>{
    const card=props.cards.map((c,i)=>(
        <Card
            key={i}
            card={c}
        />
    ))
    return(
    <div>{card}</div>
)}

export default CardList

和一个卡片组件来呈现所有卡片

import React from 'react';
import {connect} from 'react-redux';
import { showCardInfo, hideCardInfo } from '../redux/flashCardRedux';

const Card =(props)=>{
    const onCardClick=()=>{
        console.log(props.card.id)
    }
    return (
    <div>

        {props.card.showInfo?

        <div
            onClick={()=>props.dispatch(hideCardInfo(props.card.id))}
        >{props.card.name}</div>
        :
        <div
            className='card'
            onClick={()=>props.dispatch(showCardInfo(props.card.id))}
        >
            <div className='img'>
                <img src={props.card.img}/>
                <h3>{props.card.name}</h3>
            </div>
        </div>}

    </div>

)}

export default connect()(Card)

2 回答

  • 1

    对我来说,我发现最佳做法是仅在主要组件中引用 dispatch ,并仅传递子组件所需的属性 . 这不仅意味着您没有将 dispatch 传递给所有东西,而且还允许在需要时对较小的组件进行单元测试 .

    它还使较小的组件“更轻”,因为它们只有他们需要的东西,并且可以轻松地在应用程序的其他区域呈现 .

    将来,如果你想要将Redux换成类似的东西,那就意味着你只需要在主要组件中而不是在系统的任何地方编辑代码 .

  • 1
    Its always recommended to use dispatch in parent component because 
    child is also part of parent but as per requirement you can shift.
    
    as you have parent to child connection either you can connect in 
    parent and pass data as `props` or either you can take out in child 
    component itself, it depend upon how complex your parent and 
    child.however for smaller component always use as props else go for 
    component wise connect.
    
    for more info [follow this](https://reactjs.org/)
    

相关问题