【发布时间】:2021-04-15 18:44:53
【问题描述】:
我正在尝试一个 react-redux 示例代码,我想在单击“添加课程”时以一种形式添加课程,我想更新商店并重定向到包含课程列表的新页面。
但由于某种原因,重定向发生在调用 redux 操作创建者之后。它保持在同一页面中。
任何想法如何将结果重定向到不同的页面?
import React from "react";
import { connect } from "react-redux";
import * as courseActions from "../../redux/actions/courseActions";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import history from './history'
class CoursesPage extends React.Component {
state = {
course: {
title: "",
},
};
handleSubmit = (event) => {
event.preventDefault();
this.props.actions.loadCourses.createCourse(this.state.course).then(() => {
alert('Inside Promise')
history.push('/AllCourses'); //This doesn't get executed.
};
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<h2>Courses</h2>
<h3>Add Course</h3>
<input type="submit" value="Add Course" />
{this.props.courses.map((course) => (
<div key={course.title}>{course.title}</div>
))}
</form>
<hr />
</div>
);
}
}
CoursesPage.propTypes = {
courses: PropTypes.array.isRequired,
actions: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
return {
courses: state.courses,
};
}
function mapDispatchToProps(dispatch) {
return {
actions: {
loadCourses: bindActionCreators(courseActions, dispatch),
},
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CoursesPage);
Action Code:
import * as types from "./actionTypes";
export function createCourse(course) {
return { type: types.CREATE_COURSE, course };
}
Reducer:
import * as types from "../actions/actionTypes";
export default function courseReducer(state = [], action) {
debugger;
switch (action.type) {
case types.CREATE_COURSE:
return [...state, { ...action.course }];
default:
return state;
}
}
history.js
import createHistory from 'history/createHashHistory'
export default createHistory()
【问题讨论】:
-
可以分享
action code -
我刚刚更新了代码。谢谢
-
createCourse 不返回任何承诺
-
你可以简单地做
this.props.actions.loadCourses.createCourse(this.state.course); history.push('/allCourses'); -
这个动作依赖于api调用,不需要等待响应,触发动作然后推送到新路由。删除
then
标签: reactjs react-redux