在渲染功能React Redux中未使用属性时,防止组件重新渲染

时间:2020-04-21 16:30:53

标签: javascript reactjs redux react-redux

我正在努力重新渲染一个组件。
我正在使用Redux管理状态。在组件中,我正在组件(类)的某些方法中使用mapStateToProps从状态使用属性(isPlaying:bool),除了渲染功能,我使用一些动作创建者来调度 isPlaying 的更改。顺便说一句,我正在使用connect(react-redux)在另一个子组件( Music Player )中使用 isPlaying
这是我的期望
正在播放时,父组件不会重新渲染,而音乐栏 >重新渲染,我继续在父组件的方法中使用 isPlaying
出什么问题
即使我未在render方法中使用 isPlaying ,父组件也会重新渲染。
抱歉,如果我在阅读时确实让您感到困惑,我不是英语母语人士。
预先感谢。

编辑:添加代码的简化版本。
我的初始状态:

export default {
// Some Irrelevant Properties
...

playlist: {
    isPlaying: false,
    playingTrack: null,
    nextTrack: null,
    prevTrack: null,
    views: null,
    totalListens: null,
    tracks: []
}

};

这是我的父组件。 (App.js)

import ...
class App extends React.Component {
constructor(props) {
        super(props)
        this.state = {
            widgets: [],
            links: [],
            clickedTrack: null
        }

        this.musicBarRef = React.createRef()
        this._isMounted = false;

        // Binding this to the methods used in this Component
        ...

    }
    // All my methods here
    // Example of one function 
    playTrack() {
        let {isPlaying} = this.props
        if (isPlaying) {
            // Pause
        } else {
            // Play
        }
    }

    render() {
        <>
            // Some irrelevant components (don't use isPlaying)
            <TracksPlaylist tracks={this.props.tracks} and some the methods created above />
            <MusicBar ref={this.musicBarRef} and some methods created above />

            // Example of one irrelevant component that re-renders
            <Footer />
        </>
    }
}

const mapStateToProps = (state) => {
    return {
        isPlaying: state.playlist.isPlaying,
        selectedTrack: state.playlist.playingTrack,
        nextTrack: state.playlist.nextTrack,
        prevTrack: state.playlist.prevTrack,
        tracks: state.playlist.tracks,
    }
}

const mapDispatchToProps = {
    setPlaying: startPlaying, // Set isPlaying: true
    setNotPlaying: stopPlaying, // Set isPlaying: false
    // Some Irrelevent Action Creators
    ...
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

这是我的减速机

import * as types from "../actions/actionTypes";
import initialState from "./initialState";

export default function musicPlayerReducer(state = initialState.playlist, action) {
    switch (action.type) {
        // Some irrelevant cases
        ...

        case types.STOP_PLAYING:
            return {...state, isPlaying: false}
        case types.START_PLAYING:
            return {...state, isPlaying: true}
        case types.NEXT_TRACK_FOUND:
            return {...state, nextTrack: action.track}
        case types.PREV_TRACK_FOUND:
            return {...state, prevTrack: action.track}
        case types.CURRENT_TRACK_FOUND:
            return {...state, playingTrack: action.track}
        default:
            return state
    }
}

App.js中提到的TracksPlaylist

import ...

class TracksPlaylist extends React.Component {

    constructor(props) {
        super(props)
    }

    render() {
        let {tracks, onPlayClick ... and other methods from App.js} = this.props
        return (
            <div className="songs">
                {
                    Object.values(tracks).length > 0 ?
                        Object.values(tracks).map((item, index) => {
                            return <Track onPlayClick={onPlayClick} key={index} item={item} />
                        }) :
                        ''
                }
            </div>
        )
    }
}
const mapStateToProps = (state) => {
    return {
        tracks: state.playlist.tracks,
    }
}

const mapDispatchToProps = {
    setPlaying: startPlaying,
    setNotPlaying: stopPlaying,

    // Some irrelevant functions
    ...
}

export default connect(mapStateToProps, mapDispatchToProps)(Tracks)

跟踪组件

import ...

class Track extends React.Component {
    constructor(props) {
        super(props)
    }

    hasInteraction(interactionType, trackId) {
        return false
    }


    render() {
        let {onPlayClick, item} = this.props
        return (
            <div key={item.track_id} className="track" id={item.track_id} data-category={item.category_name}>
                    // A lot of irrelevant JSX :)
                    <TrackAction onPlayClick={onPlayClick} item={item} />
                </div>
            </div>
        )
    }

}

export default Track

这是TrackAction(它使用isPlaying):

import ...

function TrackAction({item, isPlaying, playingTrack, onPlayClick}) {
    return (
        <div className="status action play-track" onClick={onPlayClick}>
            <i id={item.track_id} className={isPlaying && playingTrack.track_id === item.track_id ? 'fas fa-pause' : 'fas fa-play'} />
        </div>
    )
}

const mapStateToProps = (state) => {
    return {
        isPlaying: state.playlist.isPlaying,
        playingTrack: state.playlist.playingTrack
    }
}

export default connect(mapStateToProps)(TrackAction)

我确实使用TrackAction来重新渲染该组件,因为isPlaying正在更改,并且已注册到该组件并在其render()中使用。
再次感谢。

1 个答案:

答案 0 :(得分:1)

尽管您没有在isPlaying方法中使用render,但仍在订阅由于mapStateToProps绑定而引起的更改。

每当State || Props发生变化时,React都会通过浅浅的比较重新渲染新的更新的state || props

这就是您的父母被重新渲染的原因。

一种可能的解决方案是覆盖shouldcomponentupdate

https://reactjs.org/docs/react-component.html#shouldcomponentupdate

使用shouldComponentUpdate()来让React知道组件的输出是否 不受当前状态或道具变更的影响。默认值 行为是在每次状态更改时重新渲染。

默认为true。如果覆盖并返回false,则UNSAFE_componentWillUpdate(),render()和componentDidUpdate() 不被调用。

示例代码:

shouldComponentUpdate(nextProps, nextState) {
  return <enter_your_condition_to_be_true>; // else false
}