1

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

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

和一个 Card 组件来渲染所有卡片

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)
4

2 回答 2

1

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

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

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

于 2018-01-03T16:59:55.250 回答
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/)
于 2018-01-03T17:04:00.750 回答