问题
I have a component called "categories", where I have 2 buttons active and inactive. Each button calls an api to either activates or deactivates the selected record. However, the button part and the api part are running completely fine and getting proper response after getting the task done. But, I need the "categories" component to reload/re-render after the api response has returned the success code.
I googled for the solution but the answers I got were little confusing for me because I am currently learning the ReactJS.
Here is my code:
...
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>
...
}
Also can this code be reduced/optimized..?
回答1:
I figured out the solution (I got an idea from another answer, but unfortunately I lost that link. I'll paste it if I find it again).
Here is my solution:
...
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>
}
...
)
}
I hope this may come in handy for someone. However, if there is any room for improvement then please let me know. :)
来源:https://stackoverflow.com/questions/54892155/reactjs-reloading-re-rendering-a-component-on-click