我创建了一个带有onChange事件的下拉框,以过滤数据,例如['校园A','校园B',...]。当我选择下拉列表值时,返回的数据可以正常工作,但是我的下拉列表框仅具有选定的值“校园A”和默认的“选择”值。如何解决这个问题?谢谢。 App.js
import React, { Component } from 'react';
import './App.css';
import Course from './Components/Course';
import axios from 'axios';
//import CampusName from './Components/CampusName';
class App extends Component {
constructor() {
super();
this.state ={
courses:[],
selectedCampus:''
};
}
componentDidMount(){
axios.get('myapiURL')
.then(response=>{
this.setState({courses:response.data});
});
}
_getUniqueCampusName(){
const courses=this.state.courses;
const campusSelection=[...new Set(courses.map(item=>item.CAMPUS_NAME))];
return campusSelection.map((campus,index)=>(<CampusName key={index} value=
{campus} onChange="this._campusFilter.bind(this)"/>));
}
//campus filter
_campusFilter(event){
const selection = event.target.options[event.target.selectedIndex];
let filteredData;
if (selection.value === "0") {
filteredData= this.state.courses;
return;
}
else{
filteredData = this.state.courses.filter(item=>{
return (item.CAMPUS_NAME === event.target.value);
});
}
this.setState({
selectedCampus: event.target.value,
courses: filteredData
});
}
render() {
const courses= this.state.courses.map(course=>(<Course ID={course.ID}
coursename={course.SUBJECT} />));
const campusName=this._getUniqueCampusName();
const renderCourses = courses.map((course, index) => {
return <li key={index}>{<Course key={index} ID={course.ID} SUBJECT= {course.SUBJECT} CAMPUS_NAME={course.CAMPUS_NAME} />}</li>;
});
return (
<div className="App">
<div className="filter">
<select name="campus" onChange={this._campusFilter.bind(this)}>
<option value="0">Select a Campus</option>
{campusName}
</select>
</div>
<div className="Course">Courses: {renderCourses}
</div>
</div>
);
}
}
export default App;
Course.js
import React from 'react';
const course=props=>{
return(
<div className="Course">
<p>ID: {props.ID}</p>
<p>SUBJECT: {props.SUBJECT}</p>
<p>Campus: {props.CAMPUS_NAME}</p>
</div>
);
}
export default course;