如何使用this.state更新表中的值?



我做了一个组件,它在表格中显示来自数据库的信息。但是这些信息带有过滤器。 可以按事件类型和参与者(id:整数类型)进行筛选。

当我单击按钮时,我调用handleShowClick()。在这个函数中,我检查:如果事件类型的值不为空,我从这种类型的数据库事件中获取。如果事件类型的值为空,我得到所有事件

在此之后,我检查参与者值。如果值不为空,我调用函数,该函数搜索哪些事件包含此参与者来自 this.state.event 的数据显示在另一个组件的表中。

我对事件类型没有问题。但是我对参与者有问题。当我选择其中一个参与者时,表格会在一瞬间显示正确的数据。在此之后返回到上一个状态(参与者不过滤)。

如何解决此问题?我仅在此组件中将状态设置为事件

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}, ...]
this.setState(...this.state,{ event: list }); 

我认为这将解决您的问题。因为您通过不复制以前的状态来清除除 {event:list} 之外的所有项目。

编辑:

你应该把

...this.state 

onHandleEventByeTypeFetchonHandleEventFetch.单击handleShowClick如果没有它们,这两个函数之一将始终工作,并通过不复制以前的状态从状态中清除searchByParticipant数据。

您在短时间内看到正确数据的原因完全与状态的异步性质有关。

最新更新