【问题标题】:Update the state of an object element in React在 React 中更新对象元素的状态
【发布时间】:2018-06-12 08:01:31
【问题描述】:

我正在做一个反应项目,我在数组中有一个对象我已将初始状态设置为

input: [
{item:'', label :'', codeBlock:''}
  ],

在 onClick 事件中,我设置了 javaSript 对象中元素的值的状态,并使用下面的代码将它们推送到输入数组中

Text(){

 const input = this.state.input;
 const item = <input type="text" placeholder="Enter text here!" 
className="InputDiv" onChange={this.handleTextChange.bind(this)}/>
 const codeBlock = <input type="text" placeholder="Enter text here!" 
 className="InputDiv"/>;
const label = this.state.label;
this.setState({input : input.concat({item, label, codeBlock})});
console.log(this.state.input)




}

现在我正在尝试更新 onChange 事件、handleTextChange 上的标签元素的值。我的意思是对于当前状态,在 onChange 事件上,只设置标签的值并更新状态。

请问我将如何在 React 中做到这一点?

谢谢

【问题讨论】:

  • 如果没有看到您的代码,我们将无法帮助您。您需要有一种方法来识别要更新的 which label(因为您有一个数组),大概您的代码中确实有。请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets([&lt;&gt;] 工具栏按钮)的 runnable 问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one.
  • 问题是你有一个以对象为状态的数组,我们不知道你想更新数组中的哪个元素。因此,如果我理解您的文字,我会在 onClick 事件 = onClick={ () => this.setState({input[0].label: 'your-value' })} 上这样做
  • 用数组把这个复杂化的原因是什么?

标签: javascript reactjs


【解决方案1】:

来试试这样的...

class TodoApp extends React.Component {

  state = {
        input: [],
        currentItem: '',
        currentLabel: '',
        urrentCodeBlock: ''
  }

  handleInput = (e, label) => {
    // filling out currentState of your inputs
    this.setState({[label]: e.target.value})
  }
  
  clickHandler = () => {
    // creating copy of old array of inputs
    const newArr = [...this.state.input];
    // creating new Object that u defined
    const newObj = {
    	item: this.state.currentItem,
      label: this.state.currentLabel,
    	codeBlock: this.state.currentCodeBlock,
    }
    
    // pushing your new Obj to copy of old array
    newArr.push(newObj);
    
    // updateing state and setting input values to ''
    this.setState({
    	input: newArr,
      currentItem: '',
      currentLabel: '',
      currentCodeBlock: ''
    })
  }
  
  render() {
    let InputList = this.state.input.map((input, index) => (
    	<li key={index}> {input.item} - {input.label} - {input.codeBlock}</li>
    ))
    return (
      <div>
          <input type="text" placeholder="Item" value={this.state.currentItem} onChange={(e) => this.handleInput(e, 'currentItem')} />
          <input type="text" placeholder="Label" value={this.state.currentLabel} onChange={(e) => this.handleInput(e, 'currentLabel')} />
          <input type="text" placeholder="CodeBlock" value={this.state.currentCodeBlock} onChange={(e) => this.handleInput(e, 'currentCodeBlock')} />
          <button onClick={this.clickHandler}>SAVE</button>
          <hr/>
          <ul>
            {InputList}
          </ul>
      </div>
    )
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<div id="app"></div>
<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>

【讨论】:

    【解决方案2】:

    如果您的状态对象是一个数组,您必须从索引中选择正确的对象,创建一个重复的对象并分配新值,然后使用新值设置状态。

    updateLabel=(text, index)=>{
     let allInputs = [...this.state.input];
     let selectedInput = {...allInputs[index]};
     selectedInput.label = text;
     allInputs[index] = selectedInput;
     this.setState({input:allInputs});
    }
    

    【讨论】:

      猜你喜欢
      • 2018-09-08
      • 2017-09-30
      • 2021-04-07
      • 2021-02-06
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      相关资源
      最近更新 更多