How to handle tree-shaped entities in Redux reducers?

后端 未结 2 978
我寻月下人不归
我寻月下人不归 2021-01-30 07:35

I\'m a bit stuck thinking on how to implement a reducer where its entities can have children of the same type.

Let\'s take reddit comments as an example: each comment ca

2条回答
  •  再見小時候
    2021-01-30 07:57

    The official solution to this is to use normalizr to keep your state like this:

    {
      comments: {
        1: {
          id: 1,
          children: [2, 3]
        },
        2: {
          id: 2,
          children: []
        },
        3: {
          id: 3,
          children: [42]
        },
        ...
      }
    }
    

    You're right that you'd need to connect() the Comment component so each can recursively query the children it's interested in from the Redux store:

    class Comment extends Component {
      static propTypes = {
        comment: PropTypes.object.isRequired,
        childComments: PropTypes.arrayOf(PropTypes.object.isRequired).isRequired
      },
    
      render() {
        return (
          
    {this.props.comment.text} {this.props.childComments.map(child => )}
    ); } } function mapStateToProps(state, ownProps) { return { childComments: ownProps.comment.children.map(id => state.comments[id]) }; } Comment = connect(mapStateToProps)(Comment); export default Comment;

    We think this is a good compromise. You pass comment as a prop, but component retrieves childrenComments from the store.

提交回复
热议问题