首页 > 解决方案 > 如何在 React 中的 map 函数中设置状态?

问题描述

我的代码片段如下:

状态变量:

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

内部渲染函数:

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

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

))

我想通过数组进行映射并检查数组中的特定id内容,例如,如果数组包含 an id = 1,则将状态设置valuet1,类似地,如果数组包含 an id = 2,则将状态设置valuet2

map函数内部,我们不能重复设置状态。什么是替代方案?

标签: javascriptreactjs

解决方案


您不需要(也不应该)在任何循环中设置状态。

在本例中,您只需要find匹配项,如果找到,将其值设置为状态,如下所示:

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>


推荐阅读