【问题标题】:How to update multiple child states in React Class Components independently?如何独立更新 React 类组件中的多个子状态?
【发布时间】:2020-12-21 07:37:54
【问题描述】:

我知道如何使用功能组件来完成。但是当涉及到类组件时,我有几个问题需要澄清。

我在这里上课,

class MyTable extends Component {
   constructor(props) {
      super(props);
       this.state = {
          page:0,
          rowsPerPage:10
       }
   }

   handleChangePage(event) {
      //Here I want to update only **page** keeping **rowsPerPage** intact
   }

   handleChangeRowsPerPage(event) {
      //Here I want to update only **rowsPerPage** keeping **page** intact
   }

   render() {
      return(
         <SomeComponent
           onChangePage={this.handleChangePage}
           onChangeRowsPerPage={this.handleChangeRowsPerPage}
         />
      )
   }
}
export default Mytable;

所以我想知道的是,

  1. 如果我只想更新状态对象内的 page,我是否必须保留 rowsPerPage 并将它们都更新为 this.setState({page:&lt;updatedValue&gt;, rowsPerPage:&lt;preservedValue&gt;); 反之亦然

  2. 如果我们可以更新状态对象内的独立属性,handleChangePagehandleChangeRowsPerPage 中会包含哪些代码。

  3. 当我们有几个这样的状态并且我们想要独立更新每个状态时,最佳做法是什么?

【问题讨论】:

    标签: reactjs react-state react-class-based-component


    【解决方案1】:

    您可以像我下面所做的那样独立更新pagerowsPerPage。您只需调用 this.setState 并使用您要更新的状态的 key 传递和对象

    class MyTable extends React.Component {
       constructor(props) {
          super(props);
           this.state = {
              page:0,
              rowsPerPage:10
           }
           
           this.handleChangePage = this.handleChangePage.bind(this);
           this.handleChangeRowsPerPage = this.handleChangeRowsPerPage.bind(this);
       }
    
       handleChangePage(event) {
          //Here I want to update only **page** keeping **rowsPerPage** intact
          this.setState({page: event.target.value});
       }
    
       handleChangeRowsPerPage(event) {
          //Here I want to update only **rowsPerPage** keeping **page** intact
          this.setState({rowsPerPage: event.target.value});
       }
    
       render() {
          return (
             <div>
                <div>
                  Page <input type="text" value={this.state.page} onChange={this.handleChangePage} />
                </div>
                
                <div>
                  rowsPerPage <input type="text" value={this.state.rowsPerPage} onChange={this.handleChangeRowsPerPage} /></div>
             </div>
          )
       }
    }
    
    ReactDOM.render(<MyTable />, document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 2016-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 1970-01-01
      • 2020-04-25
      相关资源
      最近更新 更多