我已经实现了Material UI Select组件,其中包含用户从中选择的类别。我遇到的问题是类别值没有被选择,因此出现以下Django后端错误
/ api / courses /中的IntegrityError,列“ category_id”中的空值违反了非空约束
我可能做错了什么?这是我正在使用的文件。
NewCourseView.js
const newCourse = ({
allcategory,
category,
handleSelectChange,
}) => {
return (
<div>
<br />
<React.Fragment>
<div className="upload-course-form">
<Typography className="form-titltle" variant="h6" gutterBottom>
CREATE COURSE
</Typography>
<Grid item xs={12} sm={6}>
<InputLabel
htmlFor="select-category"
>
Category
</InputLabel>
<Select
name="category"
value={category}
onChange={handleSelectChange}
className="select-categories"
inputProps={{
id: "select-category",
}}
>
{" "}
{allcategory.map(cate => (
<MenuItem key={cate.id} value={cate.id}>
{cate.title}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12}>
<button onClick={handleSubmit} className="submit-course-button">
{" "}
SUBMIT
</button>
</Grid>
</Grid>
</div>
</React.Fragment>
</div>
);
};
newCourse.propTypes = {
handleSubmit: PropTypes.func,
handleSelectChange: PropTypes.func.isRequired,
allcategory: PropTypes.array,
category: PropTypes.number.isRequired,
};
export default newCourse;
NewCourseContainer
export class CreateCourse extends Component {
constructor(props) {
super(props);
this.state = {
category: "",
allcategory: [],
};
}
componentWillMount() {
this.categories();
}
handleSelectChange = e => {
this.setState({ category: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
const data = {
video: {
category: this.state.category,
}
};
this.props.dispatch(createNewCourseAction(data));
};
categories = () => {
let initial = [];
fetch(API_URLS.FETCH_CATEGORIES, {
method: "GET",
headers: myHeaders
})
.then(response => {
return response.json();
})
.then(data => {
initial = data.categorys.results.map(category => {
return category;
});
this.setState({
allcategory: initial
});
})
.catch(error => {
toast.error(error, { autoClose: 3500, hideProgressBar: true });
});
};
render() {
const {
category,
allcategory
} = this.state;
return (
<div>
<NewCourse
handleSubmit={this.handleSubmit}
category={category}
allcategory={allcategory}
handleSelectChange={this.handleSelectChange}
/>
</div>
);
}
const mapDispatchToProps = dispatch => ({ dispatch });
export default connect(
mapStateToProps,
mapDispatchToProps
)(CreateCourse);
答案 0 :(得分:0)
在选择器中:
onChange={(e, k, val) => this.handleSelectChange(e, k, val)}
handleSelectChange:
handleSelectChange = (e, k, val) => {
this.setState({ category: val });
};