繁体   English   中英

如何在 React 中的 map function 中设置 state?

[英]How to set the state inside map function in React?

我的代码片段如下:

state 变量:

state = {
  value: 'default value', 
  items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}]
}

内部渲染 function:

this.state.items.map((data, key) => (

  // I want to set the state of 'value' here something like this
  this.setState({ value: 'somevalue' })

))

我想通过阵列到Z1D78DC8ED51214EFE24490AEZ,并在数组中检查一个特定的id ,如果阵列包含一个id = 2 id = 1 ,则设置Z9ED39E2EA2EA2EA931586B6B6B6A985A6942F5338 value and8 and8 and2 and2 and and ysnay zyney ys id1 ys id1 if as t1 ,如果valuet2

map function 内部,我们不能重复设置 state。 什么是替代方案?

您不需要(也不应该)在任何循环内设置 state。

在本例中,您只需find匹配项,如果找到,则在 state 中设置其值,如下所示:

 const { Component } = React class App extends Component { constructor(props) { super(props) this.state = { value: 'default value', items: [{id: 1, title: 't1'}, {id: 2, title: 't2'}] } } handleClick = (id) => { const found = this.state.items.find(item => item.id === id) if (found) { this.setState({value: found.title}) } } render() { return ( <div> value: {this.state.value} <br/> <button onClick={() => this.handleClick(1)}>Click (1)</button> <button onClick={() => this.handleClick(2)}>Click (2)</button> </div> ) } } ReactDOM.render(<App />, document.getElementById("root"))
 <script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script> <div id="root"></div>

暂无
暂无

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

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