我有一个名为“类别”的组件,其中我有2个按钮处于活动状态和非活动状态。每个按钮调用api来激活或停用所选记录。但是,按钮部分和api部分运行完全正常,并在完成任务后得到适当的响应。但是,在api响应返回成功代码后,我需要“类别”组件重新加载/重新渲染。
我用谷歌搜索解决方案,但我得到的答案对我来说有点困惑,因为我正在学习ReactJS。
这是我的代码:
...
setInactive(e)
{
Axios
.get("/api/category/deactivate/" + $(e.currentTarget).data('token'))
.then((response) => {
if (response.data.success == true)
{
this.setState({
state: this.state
});
}
});
}
setActive(e)
{
Axios
.get("/api/category/reactivate/" + $(e.currentTarget).data('token'))
.then(response => {
if (response.data.success == true)
{
this.setState({
state: this.state
});
}
});
}
render()
{
...
(category.status == "Y")
? <button data-token={category.token} className="lightRed" onClick={this.setInactive}>Inactive</button>
: <button data-token={category.token} className="green" onClick={this.setActive}>Active</button>
...
}
此代码也可以减少/优化..?
我想出了解决方案(我从另一个答案得到了一个想法,但不幸的是我丢失了那个链接。如果我再找到它,我会粘贴它)。
这是我的解决方案:
...
componentWillMount()
{
this.fetchData();
}
fetchData()
{
Axios
.get("/api/categories")
.then(response => this.setPagination(response.data));
}
setStatus(token, status)
{
Axios
.get("/api/category/status/" + token + "/" + status)
.then((response) => {
if (response.data.success == true)
{
this.setState({
message: <Alerts alertClass="alert-success">
Category status has been modified successfully.
</Alerts>
});
this.fetchData();
}
else
{
this.setState({
message: <Alerts alertClass="alert-danger">
{response.data.message}
</Alerts>
});
}
});
}
setPagination(response)
{
this.setState({
categories: response.data,
totalItemsCount: response.total,
itemsCountPerPage: response.per_page,
activePage: response.current_page,
paginationIndex: ((response.current_page - 1) > 0)
? (((response.current_page - 1) * response.per_page) + 1)
: 1
});
}
pagination(pageNumber)
{
Axios
.get("/api/categories?page=" + pageNumber)
.then(response => this.setPagination(response.data));
this.setState({
activePage: pageNumber
});
}
render()
{
return (
...
{
(category.status == "Y")
? <button className="buttons tiny lightRed" onClick={() =>
this.setStatus(category.token, 'N')
}>Inactive</button>
: <button className="buttons tiny green" onClick={() =>
this.setStatus(category.token, 'Y')
}>Active</button>
}
...
)
}
我希望这对某人来说可能会派上用场。但是,如果有任何改进的余地,请告诉我。 :)