XXx Asked: 2020-11-25 10:27:48 +0800 CST 2020-11-25 10:27:48 +0800 CST 2020-11-25 10:27:48 +0800 CST 在 React 中更新数组 772 具有以下代码, this.state = { valores: ['A', 'B', 'C'] } 我怎样才能更新这个数组的元素?那种: this.setState({ valores[1]: 'a' }) javascript 2 Answers Voted Best Answer Edgar Ortega Ramírez 2020-11-25T12:35:29+08:002020-11-25T12:35:29+08:00 我建议不要直接改变状态对象,而是将它分配给一个变量并重新分配它。 在这里您可以阅读一些不应该直接变异的原因https://daveceddia.com/why-not-modify-react-state-directly/ 您也可以使用https://github.com/kolodny/immutability-helper class MyComponent extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this) this.state = { valores: ['a', 'b', 'c'] }; } handleClick(e) { e.preventDefault(); var valores = this.state.valores; valores[0] = Math.random(); this.setState({valores: valores}); } render() { return ( <div> <div>{this.state.valores}</div> <button onClick={this.handleClick}>Cambiar primer valor</button> </div> ); } }; ReactDOM.render( <MyComponent />, document.getElementById('root') ) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> Carlos Lucero 2020-12-28T17:36:13+08:002020-12-28T17:36:13+08:00 完全不建议使用辅助变量,因为在处理更复杂状态的组件中,以这种方式改变状态变得难以管理,因为这种 React 提供了帮助您在其结构变得更复杂时改变状态的 Helpers https://facebook.github.io/react/docs/update.html 因此,例如,假设您的组件在状态中处理除“值”之外的更多变量,使用 React 的 Inmutability Helpers,实现将如下(ES6) import React from 'react' import update from 'react-addons-update' export default class ValoresComponent extends React.Component { constructor(props) { super(props); this.state = { valores: ['A', 'B', 'C'], otrosValores: { objetoAdicional: { attr: false, attr1: 1 } } } } agregarD = () => { this.setState(update( this.state, { valores: {$push: 'D'} } )) }; render() { return( <div> <div>{this.state.valores}</div> <button onClick={this.agregarD}>Agregar D</button> </div> ) } } 通过这种方式,您只需更新“值”数组并保持状态结构的其余部分不变,而无需制作不必要的副本或使用辅助变量。
我建议不要直接改变状态对象,而是将它分配给一个变量并重新分配它。
在这里您可以阅读一些不应该直接变异的原因https://daveceddia.com/why-not-modify-react-state-directly/
您也可以使用https://github.com/kolodny/immutability-helper
完全不建议使用辅助变量,因为在处理更复杂状态的组件中,以这种方式改变状态变得难以管理,因为这种 React 提供了帮助您在其结构变得更复杂时改变状态的 Helpers
https://facebook.github.io/react/docs/update.html
因此,例如,假设您的组件在状态中处理除“值”之外的更多变量,使用 React 的 Inmutability Helpers,实现将如下(ES6)
通过这种方式,您只需更新“值”数组并保持状态结构的其余部分不变,而无需制作不必要的副本或使用辅助变量。