【问题标题】: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;
所以我想知道的是,
-
如果我只想更新状态对象内的 page,我是否必须保留 rowsPerPage 并将它们都更新为
this.setState({page:<updatedValue>, rowsPerPage:<preservedValue>);
反之亦然
-
如果我们可以更新状态对象内的独立属性,handleChangePage 和 handleChangeRowsPerPage 中会包含哪些代码。
-
当我们有几个这样的状态并且我们想要独立更新每个状态时,最佳做法是什么?
【问题讨论】:
标签:
reactjs
react-state
react-class-based-component
【解决方案1】:
您可以像我下面所做的那样独立更新page 和rowsPerPage。您只需调用 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>