简体   繁体   English

在 reactjs 中动态更新/设置 state

[英]Update/set state dynamically in reactjs

I am new to reactjs and used to load/update data through javascript/jquery.我是 reactjs 的新手,曾经通过 javascript/jquery 加载/更新数据。

In my example I've got 3 buttons.在我的示例中,我有 3 个按钮。 Whenever I click one one button, I would like to update the text above.每当我单击一个按钮时,我都想更新上面的文字。 Right now, I am using same state for the counter.现在,我正在使用相同的 state 作为计数器。 Can't you somehow get the current divs ID - and update the state inside it?您不能以某种方式获取当前的 div ID - 并更新其中的 state 吗?

I could just change the state to 3 different states.我可以将 state 更改为 3 个不同的状态。 But the reason why I am not doing this is if I ever want to load something dynamically they probably have the same state?但是我不这样做的原因是,如果我想动态加载某些东西,它们可能具有相同的 state?

jsfiddle: https://jsfiddle.net/t9am76fs/1/ jsfiddle: https://jsfiddle.net/t9am76fs/1/

constructor(props) {
    super(props);

    this.state = {
        count: 0,
    };
}
incrementCounter = (value) => {
    this.setState({ count: this.state.count + value })
};

render() {
    return (
        <div>
            <div id='div1'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>

            <div id='div2'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>

            <div id='div3'>
                  <p>You clicked {this.state.count} times</p>
                  <button onClick={() => this.incrementCounter(1)}>+1</button>
            </div>
        </div>
    );
}

Thanks谢谢

You can also do it by giving the input names and accessing these via the event.target.name and use that to update state depending on the given name.您也可以通过提供输入名称并通过 event.target.name 访问这些名称并使用它来根据给定名称更新 state 来做到这一点。

 class Counter extends React.Component { constructor(props) { super(props); this.state = { count: [0,0,0] }; } incrementCounter = (event) => { const updatedCount = [...this.state.count] // Create a shallwo copy updatedCount[Number(event.target.name)]++ this.setState({ count: updatedCount }) }; render() { const [count1, count2, count3] = this.state.count; return ( <div> <div id='div1'> <p>You clicked {count1} times</p> <button name='0' onClick={this.incrementCounter}>+1</button> </div> <div id='div2'> <p>You clicked {count2} times</p> <button name='1' onClick={this.incrementCounter}>+1</button> </div> <div id='div3'> <p>You clicked {count3} times</p> <button name='2' onClick={this.incrementCounter}>+1</button> </div> </div> ); } } ReactDOM.render(<Counter />, document.querySelector("#app"));
 <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="app"></div>

Try it:试试看:

 class Counter extends React.Component { constructor(props) { super(props); this.state = { count1: 0, count2: 0, count3: 0, }; } incrementCounter = (type) => { this.setState({ [type]: this.state[type] + 1 }) }; render() { return ( <div> <div id='div1'> <p>You clicked {this.state.count1} times</p> <button onClick={() => this.incrementCounter('count1')}>+1</button> </div> <div id='div2'> <p>You clicked {this.state.count2} times</p> <button onClick={() => this.incrementCounter('count2')}>+1</button> </div> <div id='div3'> <p>You clicked {this.state.count3} times</p> <button onClick={() => this.incrementCounter('count3')}>+1</button> </div> </div> ); } } ReactDOM.render(<Counter />, document.querySelector("#app"));

It looks like you want to render dynamic elements, like you would do if you gather data from an API from example.看起来您想要渲染动态元素,就像您从示例中的 API 收集数据一样。

What I would do is to group the data you need dynamically into an array of objects , and you can keep the counter for each of those objects inside the object itself.我要做的是将您需要的数据动态分组到一个对象数组中,您可以将每个对象的计数器保存在 object 本身内。

In the example below.在下面的例子中。 You map the array and each onClick will update its own object counter.您的 map 阵列和每个 onClick 将更新其自己的 object 计数器。 This way you don't need to explicitly write the state for every single element.这样,您无需为每个元素显式编写 state。

This is just a sample and you can improve it later:这只是一个示例,您可以稍后对其进行改进:

const dynamicDivsInfo = [
  { name: "Example", id: "div1", count: 0 },
  { name: "Example 2", id: "div2", count: 0 }
];

class Example extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      divs: [...dynamicDivsInfo]
    };
  }
  incrementCounter = (value, index) => {
    const divs = [...this.state.divs];
    divs[index].count += value;
    this.setState({ divs });
  };

  render() {
    return (
      <div>
        {this.state.divs.map((element, index) => {
          return (
            <div id={element.id}>
              <p>
                You clicked {element.name}: {element.count} times
              </p>
              <button onClick={() => this.incrementCounter(1, index)}>
                +1
              </button>
            </div>
          );
        })}
      </div>
    );
  }
}

Here is a code sandbox example: https://codesandbox.io/s/goofy-night-1hfoc?file=/src/App.js:244-1086这是一个代码沙箱示例: https://codesandbox.io/s/goofy-night-1hfoc?file=/src/App.js:244-1086

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM