React上下文如何知道我引用react-router将我重定向到另一个URL

时间:2016-08-15 06:54:07

标签: reactjs redux react-router

对于我的组件,我设置了一个上下文

ManageCoursePage.contextTypes = {
    router: PropTypes.object
};

我的类方法如何知道我引用反应路由器以自动将我重定向到另一个URL?

this.context.router.push('/courses');

这是我的组件代码:

import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as courseActions from '../../actions/courseActions';
import CourseForm from './courseForm';


class ManageCoursePage extends React.Component {
    constructor(props, context) {
        super(props, context);

        // set up local state
        this.state = {
            errors: {},
            course: Object.assign({}, this.props.course)
        };

        this.updateCourseState = this.updateCourseState.bind(this);
        this.saveCourse = this.saveCourse.bind(this);

    }

    updateCourseState(event) {
        const field = event.target.name;
        let course = this.state.course;
        course[field] = event.target.value;
        return this.setState({
            course: course
        });
    }

    saveCourse(event) {
        event.preventDefault();
        this.props.actions.saveCourse(this.state.course);
        this.context.router.push('/courses');
    }

    render() {
        return (
            <CourseForm
                allAuthors={ this.props.authors }
                onChange={ this.updateCourseState }
                onSave={ this.saveCourse }
                course={ this.state.course }
                errors={ this.state.errors }

            />
        );
    }
}

ManageCoursePage.propTypes = {
    // myProp: PropTypes.string.isRequired
    course: PropTypes.object.isRequired,
    authors: PropTypes.array.isRequired,
    actions: PropTypes.object.isRequired
};

// Pull in the React Router context so router is available on this.context.router
// basically a global variable to make it easy for other components to get data easily
ManageCoursePage.contextTypes = {
    router: PropTypes.object
};

function mapStateToProps(state, ownProps) {
    // empty course
    let course = {
        id: "",
        watchHref: "",
        title: "",
        authorId: "",
        length: "",
        category: ""
    };

    const authorsFormattedForDropDown = state.authors.map(author => {
        return {
            value: author.id,
            text: author.firstName + " " + author.lastName
        };
    });

    return {
        course: course,
        authors: authorsFormattedForDropDown
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(courseActions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(ManageCoursePage);

1 个答案:

答案 0 :(得分:1)

非常有趣的问题。 :)

它有效,因为 $.ajax({ type: 'GET', url: "/get-user-sessions/" + userId, success: function(data) { $.each(data, function(index, item) { var opt = $('#create-event-session-name option[value="'+item.session_name+'"]'); if(opt.length) {opt.attr('selected',true).attr('disabled',true);} }); }, error: function(jqXHR, textStatus, errorThrown) { } }); router库中定义为childContext类型。如果您在组件中映射react-routergetChildContext将在应用程序内部访问它。

这有助于避免将道具从父组件深深传递到深层子组件。

请参阅contextTypeshttps://github.com/reactjs/react-router/blob/master/modules/RouterContext.js#L36

还有文档https://facebook.github.io/react/docs/context.html