我应该在哪里发送我的redux

时间:2018-01-03 16:55:41

标签: reactjs redux react-redux react-props

我正在学习反应和减少,我只是有一个小问题,我应该在哪里发送和共享我的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 个答案:

答案 0 :(得分:1)

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

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

将来,如果您想要将Redux换成类似的东西,则意味着您只需编辑主组件中的代码,而不是系统中的任何位置。

答案 1 :(得分: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/)