D
D
Deodatuss2017-08-28 17:40:06
JavaScript
Deodatuss, 2017-08-28 17:40:06

What is the best way to organize the reuse of stateless components?

Good day. During the development process, I make sure that the components do not have a state and absolutely all data and states are stored in the store and transmitted through props. But here there is a difficulty in reusing components. A banal example: a table component with pagination, filters and sorting. To embed it on the page, I need to add 6 status fields and 10 actions, each time. How I decided to fix this problem. There is a reducer in the store with the "tables" key, a unique key is passed to the table container, then the state of this table is created using this unique key, taking into account other parameters that are passed to the container, it looks something like this:

class TableContainer extends React.Component {
    componentWillMount() {
        let {dispatch, tableId, initialState} = this.props;
        dispatch(TableActions.createTable(tableId, initialState));
    }
    componentWillUnmount() {
        let {dispatch, tableId} = this.props;
        dispatch(TableActions.removeTable(tableId));
    }
    changeCurrentPage(pageNumber) {
        let {dispatch, tableId} = this.props;
        dispatch(TableActions.changeCurrentPage(tableId, pageNumber));
     }
    ... хендлеры
    render(){
        return <Table {...this.props} {...this.props.tableData} {...хендлеры}/>
    }
}

const mapStateToProps = (state, ownProps) => {
  return {
         tableData: TableSelectors.getTableState(state, ownProps.tableId)
   }
}

export default connect(mapStateToProps)(TableContainer);

The question is, is this normal, or is it trash? I'm wondering how it can be done better or easier. I was inspired to do this after using redux-form.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vlad Feninets, 2017-08-28
@fnnzzz

no one forbids using the state of a component with Redux.
if the state of the component is needed by someone else besides itself, then you pass it to the Store, if it is a trite dropdown and its state (open / closed) is needed only by itself, then there is no need for it to use redux - just use setState and rejoice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question