在redux中的许多小型可重用reactjs组件上使用connect()是个好主意吗

Is it a good idea to use connect() on many small reusable reactjs components in redux

本文关键字:connect 好主意 reactjs redux 许多小 组件      更新时间:2023-09-26

假设我有一个名为<LikePanel>的小型可重用组件,它将在不同类型的父组件(如<BlogEntry><ItemEntry><ReplyEntry>)的多个页面上使用。

import {connect} from 'react-redux'
import {likeAction} from './LikeAction'

class LikePanel extends React.Component{
    render() {
        return <ButtonGroup className={this.props.className}>
            <Button onClick={()=>this.onClickLiking()}>
                <Glyphicon glyph="thumbs-up"/>{this.props.like}</Button>
            </ButtonGroup>
    }
    onClickLiking(type){
       this.props.dispatch(likeAction());
    }
}
const mapStateToProps = state => {
   let obj = {};
   obj[LIKE] = state[LIKE];
   return obj;
}
export default connect(mapStateToProps)(LikePanel)

LikePanel:的示例用例

class BlogEntry extends React.Component{
    render(){
       return this.props.data.entry.map((item)=>{
           return <div>
                       {item.article}
                       <LikePanel like={item.like}/>
                  </div> 
       }
    }
}

class ProductEntry extends React.Component{
    render(){
       return this.props.data.entry.map((item)=>{
           return <div>
                       <ProductPanel data={item}/>
                       <LikePanel like={item.like}/>
                  </div> 
       }
    }
}

因此,如果一个网页有20个博客条目,那么页面上就会有20个连接的<LikePanel>,并且将来可能会有额外的组件连接到redux。将connect()<LikePanel>这样的小组件一起使用是一种好的做法吗?

这绝对不错。在组件层次结构中任何有意义的地方使用connect。一种常见的模式是连接一个列表组件,并使用mapState检索列表中数据项的ID,为每个项呈现一些<ListItem id={itemId} />子组件,还连接每个子组件,并按ID查找其自己的数据。另请参阅https://redux.js.org/faq/react-redux#should-i-only-connect-my-top-component或can-i-connect-multiple-components-in-my-tree。

相关文章: