Prevent react component from rendering twice when using redux with componentWillMount

前端 未结 3 1151
生来不讨喜
生来不讨喜 2020-12-24 05:56

I have a React component that dispatches a redux state change in its componentWillMount function. The reason is that when the component is loaded, it needs to g

3条回答
  •  無奈伤痛
    2020-12-24 06:43

    One thing you might do is create a higher order component that handles the basic pattern of loading a different component (or no component) before the required props are loaded.

    export const LoaderWrapper = function(hasLoaded, Component, LoaderComponent, onLoad) {
        return props => {
            if (hasLoaded(props)) {
                return 
            }
            else {
                if (onLoad) onLoad(props)
    
                return { LoaderComponent ?  : null }
            }
        }
    }
    

    Then you can wrap your component before connecting it to get the desired behaviour.

    export default connect(state => ({item: state.item}))(LoaderWrapper(
        ((props) => !!props.item),
        Editor,
        null,
        (props) => props.dispatch(editItem(props.params.id))
    ))
    

    You might want to add some currying magic to make sure you can compose these kinds of wrapper functions more nicely. Take a look at recompose for more info.

提交回复
热议问题