首页 > 解决方案 > 将 State 对象数组转换为

  • 反应JS
  • 问题描述

    我是 ReactJS 的新手,我正在制作简单的待办事项应用程序,我已经实现了添加、删除、编辑功能。现在我正在搞乱分页。我被困在显示部分。

    state = {
            inputValue: '',
            todos: [],
            currentPage:1,
            pageCount:1,
        };
    
        inpRef = createRef();
    
        setPageCount = () => {
                let {todos} = this.state
              this.setState({pageCount: Math.ceil(todos.length / 5)})
                console.log('--------this.state.pageCount', this.state.pageCount );
        }
    
    paginationDisplay = () => {
        let {todos,currentPage} = this.state
        const start = this.setState({currentPage:(currentPage - 1)*5 })
        const end = start+5
        todos.forEach((item,index) => {
            if(index >= start && index < end) {
                item.style.display = "block";
            } else {
                item.style.display = "none";
            }
        })
    }
    
            renderPagination = () => {
        let {pageCount,currentPage} = this.state
    
        const paging = []
    
        for (let i=1;i<pageCount; i++){
            paging.push(
                <button key={uuidv4()}
                    className={'btn btn-info'}
                    onClick={() => {
                        this.paginationDisplay()
                        currentPage = i}}>
                    {i}
                </button>
            )
        }
        return paging
    }
    
    
    
            }
    addItem = () => {
            let {inputValue, todos} = this.state
            if (this.inpRef.current.value === '') {
                return alert('We dont do that here....')
            } else {
                this.setState({todos: [...todos, {inputValue, id: uuidv4()}]})
                this.inpRef.current.value = ''
            }
            this.setPageCount()
            this.paginationDisplay()
        }
    
                render() {
                const { todos } = this.state;
    
                return <div className={"App"}>
                    <div className="App-header">
                        <h2>Welcome to To-Do List App</h2>
                    </div>
                    <input ref={this.inpRef} onKeyPress={this.handleKeyPress} onChange={this.handleInputValue} name={''} type='text'/>
                    <button onClick={() => this.addItem()} className={'btn btn-primary'}>Add</button>
                    <ul>
                        {
                            todos.map(todoItem => <ListItem
                                key={todoItem.id}
                                todoItem={todoItem}
                                deleteItem={this.deleteItem}
                                editItem={this.editItem}
                                submitEdit={this.submitEdit}
                            />)
                        }
                        {this.renderPagination()}
                    </ul>
                </div>
            };
        }
    

    我希望此函数从中获取所有元素<ul>并更改其样式显示,当我得到时,我正在尝试改变数组中状态元素的样式。但我不知道如何从中获取所有元素<li>。请<ul>帮助

    paginationDisplay = () => {
            let {todos,currentPage} = this.state
            const start = this.setState({currentPage:(currentPage - 1)*5 })
            const end = start+5
            todos.forEach((item,index) => {
                if(index >= start && index < end) {
                    item.style.display = "block";
                } else {
                    item.style.display = "none";
                }
            })
        }
    

    标签: javascriptreactjs

    解决方案


    您可以将分页作为单独的组件

    例子

    const { Component, createRef, useState, useEffect } = React;
    
    const uuidv4 = (() => {
      let id = 0;
      
      return () => id++;
    })()
    
    const Pagination = ({page, onPageSelected, pageCount}) => {
    
      if(pageCount <= 1) {
        return null;
      }
    
      const computeClass = (currentPage) => `${page === currentPage ? 'selected' : ''} btn btn-info`
    
      return <div>
        {[...Array(pageCount).keys()].map(pr => <button key={pr}
          className={computeClass()}
          disabled={page === pr}
          onClick={() => onPageSelected(pr)}>
          {pr + 1}
        </button>)}
      </div>
    }
     
    const ListItem = ({todoItem, editItem, submitEdit, deleteItem}) => {
      return <div>{todoItem.inputValue}</div>
    }
    
    class App extends Component {
    
      constructor(props) {
        super(props);
    
        this.state = {
          inputValue: '',
          todos: [],
          pagedTodos: [],
          currentPage: 0,
          pageCount: 0,
          pageSize: 1
        };
    
        this.inpRef = createRef();
        this.handleInputValue = this.handleInputValue.bind(this);
        this.onPageSelected = this.onPageSelected.bind(this);
      }
    
      handleInputValue({target: {value: inputValue}}) {
        this.setState(state => ({...state, inputValue}))
      }
    
      addItem = () => {
            const { inputValue, pageSize } = this.state;
            
            if (this.inpRef.current.value === '') {
                return alert('We dont do that here....')
            } else {
                const todo = { inputValue, id: uuidv4() };
    
                this.setState(state => {
                  const todos = [...state.todos, todo];
                  const pageCount = Math.ceil(todos.length / pageSize);
                  const currentPage = pageCount - 1; // set last page
                  const from = currentPage * pageSize
                  const to = from + pageSize;
                  const pagedTodos = todos.slice(from, to);
                
                  return {
                    ...state,
                    todos,
                    currentPage,
                    pagedTodos,
                    pageCount
                  }}
                )
                this.inpRef.current.value = ''
            }
        }
        
        onPageSelected(currentPage) {
          this.setState(state => {
            const { pageSize, todos } = state;
            const from = currentPage * pageSize
            const to = from + pageSize;
            const pagedTodos = todos.slice(from, to);
            
            return {
              ...state,
              currentPage,
              pagedTodos
            }
          })
        }
    
        render() {
                const { pagedTodos, currentPage, pageCount } = this.state;
    
                return <div className={"App"}>
                    <div className="App-header">
                        <h2>Welcome to To-Do List App</h2>
                    </div>
                    <input ref={this.inpRef} onKeyPress={this.handleKeyPress} onChange={this.handleInputValue} name={''} type='text'/>
                    <button onClick={this.addItem} className={'btn btn-primary'}>Add</button>
                    <ul>
                        {
                            pagedTodos.map(todoItem => <ListItem
                                key={todoItem.id}
                                todoItem={todoItem}
                                deleteItem={this.deleteItem}
                                editItem={this.editItem}
                                submitEdit={this.submitEdit}
                            />)
                        }
                        <Pagination onPageSelected={this.onPageSelected} page={currentPage} pageCount={pageCount}/>
                    </ul>
                </div>
            };
        }
    
    ReactDOM.render(
        <App />,
        document.getElementById('root')
      );
    <script src="https://unpkg.com/react/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <div id="root"></div>


    推荐阅读