【发布时间】:2018-12-04 06:16:02
【问题描述】:
我制作了一个组件,它在表格中显示来自数据库的信息。但是这个信息带有过滤器。 过滤可以按事件类型和参与者(id:整数类型)。
当我单击按钮时,我调用 handleShowClick()。在这个函数中,我检查:如果 type event 的值不为空,我会从数据库 events 中获取该类型。如果 type event 的值为 null,我会得到所有 events。
在此之后,我检查一个 participant 值。如果 value 不为 null,我调用函数,搜索哪些 events 包括这个 participant。 this.state.event show 中的数据在另一个组件的表中。
事件类型我没有问题。但我对 participant 有意见。当我选择 participant 之一时,表格会在瞬间显示正确的数据。在此之后返回上一个状态(没有参与者过滤)。
我该如何解决这个问题?我仅在此组件中将状态设置为 事件
class TestPage extends Component {
constructor(props) {
super(props);
this.state = {
event: [],
searchByType: null,
searchByParticipant: null,
participantToEvent: []
};
this.handleShowClick = this.handleShowClick.bind(this);
this.onHandleEventByTypeFetch = this.onHandleEventByTypeFetch.bind(this);
this.handleParticipantSearch = this.handleParticipantSearch.bind(this);
this.onHandleEventFetch = this.onHandleEventFetch.bind(this);
}
handleShowClick() { // onClick
if (this.state.searchByType !== null) {
this.onHandleEventByTypeFetch(); // select * from ... where type=...
} else {
this.onHandleEventFetch(); // select * from ...
}
if (this.state.searchByParticipant !== null) {
this.handleParticipantSearch();
}
}
handleParticipantSearch() {
const list = [];
this.state.participantToEvent.map(itemP => { // participantToEvent is binding table
if (itemP.parid === this.state.searchByParticipant) {
this.state.event.map(itemEvent => {
if (itemEvent.id === itemP.eventid) {
list.push(itemEvent);
}
});
}
});
console.log(list); // here I see array with correct result
this.setState({ event: list });
}
onHandleEventFetch() {
fetch( ... , {
method: 'GET'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then(data => {
if (data.length === 0) {
alert('nothing');
} else {
this.setState({
event: data
});
}
});
}
onHandleEventByTypeFetch() {
fetch( ... , {
method: 'GET'
})
.then((response) => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then(data => {
if (data.length === 0) {
alert('nothing');
} else {
this.setState({
event: data
});
}
});
...
}
}
this.state.event的结构:
[{id: 1, name: 'New event', participant: 5, type: 10}, ...]
this.state.participantToEvent 的结构:
[{id: 1, idparticipant: 5, idevent: 1}, ...]
【问题讨论】:
标签: javascript reactjs