Prevent react component from rendering twice when using redux with componentWillMount

前端 未结 3 1138
生来不讨喜
生来不讨喜 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:41

    It looks like there's already an issue in the react-redux library.

    https://github.com/rackt/react-redux/issues/210

    0 讨论(0)
  • 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 <Component {...props} />
            }
            else {
                if (onLoad) onLoad(props)
    
                return { LoaderComponent ? <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.

    0 讨论(0)
  • What does editItem do? Does it add item to the redux state or is it there already?

    If it is adding I imagine what is happening is that a render cycle happens with the current props, ie item being blank. Then it gets rendered again when the props have changed, via setting the item.

    One approach to fixing this sort of thing is to create a higher order component that wraps Editor and calls the dispatch action the rendering though is set either to a loading screen or and empty div until item is set. That way you can be assured that Editor will have an item.

    But without knowing what editItem does it's sort of hard to know. Maybe you could paste the code for that?

    0 讨论(0)
提交回复
热议问题