简体   繁体   English

如何在反应中更新 state?

[英]How to update the state in react?

I'd like to update the state and display the current state in a React Fragment inside a method.我想更新 state 并在方法内的 React 片段中显示当前的 state。 I'm updating the state in reserve method and I'd like to display the new value on a button click.我正在以保留方法更新 state,我想在单击按钮时显示新值。 I was trying to do that in the span in fetchData() method but when I click the button, I don't see the updated value.我试图在 fetchData() 方法的范围内执行此操作,但是当我单击按钮时,我看不到更新的值。 Below is the screen shot of the application and code.下面是应用程序和代码的屏幕截图。 在此处输入图像描述

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

Don't store jsx in your state, store the data and let React handle the render, so, just do this in your fetchData function不要将 jsx 存储在 state 中,存储数据并让 React 处理渲染,因此,只需在fetchData function 中执行此操作

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

and in your render在你的渲染中

<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>

This will re-render when the state changes and will display the correct value这将在 state 更改时重新渲染,并将显示正确的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM