且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ReactJS:单击即可重新加载/重新渲染组件

更新时间:2023-12-02 20:03:46

我想出了解决方案(我从另一个答案中得到了一个主意,但不幸的是我丢失了该链接.如果找到它,我将其粘贴.再次).

这是我的解决方案:

...

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. :)