如果redux中的状态是不可变的,我将如何与有状态API交互?

如果redux中的状态是不可变的,我将如何与有状态API交互?,redux,react-redux,Redux,React Redux,因此,在这个应用程序中,我使用MediaRecorder api()。我正在尝试使用React Redux作为站点的框架。以下是我的reducer的简化版本,以说明我的问题: (state = {}, action) => { switch(action.type){ case "START_RECORDING": return new MediaRecorder(...).start(); case "STOP_RECORD

因此,在这个应用程序中,我使用MediaRecorder api()。我正在尝试使用React Redux作为站点的框架。以下是我的reducer的简化版本,以说明我的问题:

(state = {}, action) => {
    switch(action.type){
        case "START_RECORDING":
            return new MediaRecorder(...).start();
        case "STOP_RECORDING":
            state.stop(); <--- is this ok?
            return {};
    }
    return state;
})
(状态={},动作=>{
开关(动作类型){
案例“开始记录”:
返回新的MediaRecorder(…).start();
案例“停止录制”:

state.stop();不,这绝对是一个不好的模式

根据Redux常见问题解答,.So,您可以在存储中跟踪一个值,如
{playing:true}
,但实际上不应该在其中保留类实例

“权利”实现这一点的方法是使用一个React组件,该组件围绕命令式MediaRecorder API,从Redux存储中接收作为道具的值,并在其React生命周期方法中调用MediaRecorder函数,如
componentWillReceiveProps
。我在我的博客文章中展示了一些如何做到这一点的示例,并提供了到其他方法的链接类似的文章在我的部分

下面是一个简单的示例:

class MediaRecorderWrapper extends React.Component {
    componentDidMount() {
        this.mediaRecorder = new MediaRecorder();

        if(this.props.playing) {
            this.mediaRecorder.start();
        }
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.playing !== this.props.playing) {
            if(nextProps.playing) {
                this.mediaRecorder.start();
            }
            else {
                this.mediaRecorder.stop();
            }
        }
    }
}

const mapState = (state) => {
    return {
        playing : state.playing
    };
}

export default connect(mapState)(MediaRecorderWrapper);

非常感谢。我想知道这是否真的需要成为一个组件,因为它可能只是一个javascript类,提供媒体录制器作为一项服务。(我在angular方面有更多的经验,所以我认为服务模式是一个好主意?在react redux中不确定)使其成为React组件的最大原因是使用React的生命周期方法来控制MediaRecorder实例,并使用React Redux来处理对应用商店的订阅。对于普通JS类,您当然可以使用相同的方法,但您必须自己实现应用商店订阅逻辑和生命周期处理。