使用react-redux触发事件操作

Blu*_*sky 5 reactjs redux material-ui react-redux

我正在使用react / redux / react-redux来实现执行ajax请求的模式形式。

如果我是正确的,则react-redux使您能够:

  • 显示数据从redux存储到您的组件
  • 将事件从容器分派到redux

我还使用redux-saga处理由redux触发的Ajax请求。

但是,我不知道从Redux触发特定事件时如何触发动作(例如:关闭模式形式)。

代码示例:

class MyFormDialog extends React.Component {
    state = {
        open: false,
    };


    handleOpen = () => {
        this.setState({open: true});
    };

    handleClose = () => {
        this.setState({open: false});
    };

    render() {
        const actions = [
            <FlatButton
                label="Cancel"
                onTouchTap={this.handleClose}
            />,
            <FlatButton
                label="Submit"
                onTouchTap={this.props.ajaxRequest}
            />,
        ];

        return (
            <div>
                <MenuItem primaryText="Make a request"  onTouchTap={this.handleOpen}/>
                <Dialog
                    title="Make a request"
                    actions={actions}
                    modal={true}
                    open={this.state.open}
                    onRequestClose={this.handleClose} />
            </div>
        );
    }
}

const mapStateToProps = (state, ownProps) => {
    return {
        loading: state.isLoading,
        success: state.success,
        error: state.error,
    }
};

const mapDispatchToProps = (dispatch, ownProps) => {
    return {
        ajaxRequest: (url, tags) => {
            dispatch({type: "AJAX_REQUESTED"})
        },
    }
};

const ConnectedMyFormDialog = connect(
    mapStateToProps,
    mapDispatchToProps
)(MyFormDialog );

export default ConnectedMyFormDialog ;
Run Code Online (Sandbox Code Playgroud)

减速器的构造如下:

  • isLoading = trueAJAX_REQUESTED发送(别人都设置为false)
  • success = trueAJAX_SUCCESS发送(别人都设置为false)
  • error = trueAJAX_FAIL发送(别人都设置为false)

所以我想改变state.open为假时,isLoading改变从truefalseAND success变化falsetrue

我不知道如何在不搞乱状态的情况下做到这一点。

编辑:

这是我的sagas代码,用于处理事件:

function* handleAjaxRequest(action) {
    try {
        yield call(api.doRequest);
        yield put({type: "AJAX_SUCCESS"});
    } catch (e) {
        yield put({type: "AJAX_FAILED"});
    }
}

export default function* () {
    yield [
        takeEvery("AJAX_REQUESTED", handleAjaxRequest),
    ]
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以利用componentWillReceiveProps()在组件获得redux属性/状态更新后立即调用的方法。在那里,您可以对redux状态更改做出反应,并相应地设置本地组件状态。

在您的示例中,它将是:

componentWillReceiveProps(nextProps) {
  if (nextProps.loading !== this.props.loading &&
      nextProps.success !== this.props.success &&
      !nextProps.loading && nextprops.success) {
    this.setState({ open: false });
  }
}
Run Code Online (Sandbox Code Playgroud)

这正是您定义的想要的行为。Imo您还应该处理其他情况并更动态地设置state.open,但这超出了问题的范围。

供参考,请参见此处:https : //facebook.github.io/react/docs/react-component.html#componentwillreceiveprops