如何更新反应状态?

时间:2020-07-13 22:48:05

标签: reactjs state

我想更新状态并在方法内的React Fragment中显示当前状态。我正在使用reserve方法更新状态,并且希望在单击按钮时显示新值。我试图在fetchData()方法的跨度中执行此操作,但是当我单击按钮时,看不到更新后的值。下面是应用程序和代码的屏幕截图。 enter image description here

class BooksComponent extends Component{

    constructor(props){
        super(props)
        this.state ={
            booksData: [],
            offset: 0,
            perPage: 3,
            currentPage: 0,
        }
        this.reserve = this.reserve.bind(this)
        this.fetchData = this.fetchData.bind(this)
    }

    fetchData(){
        axios.get('/library')
          .then(res => {
            const booksData = res.data
            const slice = booksData.slice(this.state.offset, this.state.offset + this.state.perPage)
            const books = slice.map(book => 
            <React.Fragment key={book.id}>
                <p>{book.id} - {book.title} - {book.author}</p>
                <button onClick={() => this.reserve(book.id)}>Reserve {book.quantity}</button>
                <span>{this.state.booksData.quantity}</span>
            </React.Fragment>)

            this.setState({ 
                pageCount: Math.ceil(booksData.length / this.state.perPage),
                books })
          })
    }

    handlePageClick = (e) => {
        const selectedPage = e.selected;
        const offset = selectedPage * this.state.perPage;

        this.setState({
            currentPage: selectedPage,
            offset: offset
        }, () => {
            this.fetchData()
        });
    };
    
    componentDidMount() {
        this.fetchData()
    }
    
    render() {
        return (
          <div className="App">
              {this.state.books}
            <ReactPaginate
                    previousLabel={"prev"}
                    nextLabel={"next"}
                    breakLabel={"..."}
                    breakClassName={"break-me"}
                    pageCount={this.state.pageCount}
                    marginPagesDisplayed={2}
                    pageRangeDisplayed={5}
                    onPageChange={this.handlePageClick}
                    containerClassName={"pagination"}
                    subContainerClassName={"pages pagination"}
                    activeClassName={"active"}/>
          </div>
        )
    }

    reserve(id) {
        console.log("clicked")
        this.setState({
            booksData: this.state.booksData.map(item => {
                if (item.id === id) {
                    return { ...item, quantity: (item.quantity - 1) >= 0 ? (item.quantity - 1) : 0};
                } else {
                    return item;
                }
            })
        })
    }
}


export default BooksComponent

1 个答案:

答案 0 :(得分:1)

不要在您的状态下存储jsx,存储数据并让React处理渲染,因此,只需在您的fetchData函数中执行

this.setState({ 
  pageCount: Math.ceil(booksData.length / this.state.perPage),
  books
})

以及您的渲染中

<div className="App">
  {this.state.books.map(book => 
    <React.Fragment key={book.id}>
      <p>{book.id} - {book.title} - {book.author}</p>
      <button onClick={() => this.reserve(book.id)}>Reserve {book.quantity}</button>
      <span>{this.state.booksData.quantity}</span>
    </React.Fragment>
  )}
  <ReactPaginate...
</div>

状态更改时,它将重新呈现并显示正确的值