如何在 reactjs 中更新 map 函数中的状态

How to update state in map function in reactjs

我有 4 个按钮,每个按钮都有名称 ID 和 selected 布尔标志。

我想要实现的是,在单击按钮时,应该更改该特定按钮的布尔按钮标志。为此,我需要在地图函数中为该特定按钮 ID 设置状态。

我的问题是我无法在地图函数中为那个特定的点击按钮设置状态,它的 btnSelected 应该改变

我的目标是为用户创建一个多select deselect button.Its 兴趣 selection 并在此基础上反映 UI 以及我的数组。这是我的代码。

感谢期待。

import React, { Component } from "react";
import { Redirect } from "react-router-dom";

export default class Test extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleChange = this.handleChange.bind(this);
    this.state = {
      value: "",
      numbers: [1, 2, 3, 4, 5],
      posts: [
        {
          id: 1,
          topic: "Animal",
          btnSelected: false
        },
        {
          id: 2,
          topic: "Food",
          btnSelected: false
        },
        {
          id: 3,
          topic: "Planet",
          btnSelected: false
        },
        { id: 4, topic: "Nature", btnSelected: false }
      ],
      allInterest: []
    };
  }

  handleChange(e) {
    //console.log(e.target.value);
    const name = e.target.name;
    const value = e.target.value;
    this.setState({ [name]: value });
  }

  getInterest(id) {
    this.state.posts.map(post => {
      if (id === post.id) {
        //How to setState of post only btnSelected should change
      }
    });
    console.log(this.state.allInterest);
    if (this.state.allInterest.length > 0) {
      console.log("Yes we exits");
    } else {
      console.log(id);
      this.setState(
        {
          allInterest: this.state.allInterest.concat(id)
        },
        function() {
          console.log(this.state);
        }
      );
    }
  }

  render() {
    return (
      <div>
        {this.state.posts.map((posts, index) => (
          <li
            key={"tab" + index}
            class="btn btn-default"
            onClick={() => this.getInterest(posts.id)}
          >
            {posts.topic}
            <Glyphicon
              glyph={posts.btnSelected === true ? "ok-sign" : "remove-circle"}
            />
          </li>
        ))}
      </div>
    );
  }
}

这是你如何做这样的事情:

class App extends Component {
  state = {
    posts: [{
      name: 'cat',
      selected: false,
    }, {
      name: 'dog',
      selected: false
    }]
  }

  handleClick = (e) => {
    const { posts } = this.state;
    const { id } = e.target;
    posts[id].selected = !this.state.posts[id].selected
    this.setState({ posts })
  }

  render() {
    return (
      <div>
        <form>
          {this.state.posts.map((p, i) => {
            return (
              <div>
                <label>{p.name}</label>
                <input type="radio" id={i} key={i} checked={p.selected} onClick={this.handleClick} />
              </div>
            )
          })}
        </form>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

工作示例here

您可以通过将地图中的索引传递到每个按钮的 handleClick 函数来实现此目的,然后该函数将 return 另一个可以由 onClick 事件触发的函数。

与 Colin Ricardo 的回答相反,此方法避免在 map 函数的每个子函数上添加 id 道具,该道具仅用于确定 handleClick 中的索引。我在这里修改了 Colin 的示例以显示比较。请注意不再需要事件参数。

class App extends Component {
  state = {
    posts: [{
      name: 'cat',
      selected: false,
    }, {
      name: 'dog',
      selected: false
    }]
  }

  handleClick = (index) => () => {
    const { posts } = this.state;
    posts[index].selected = !this.state.posts[index].selected
    this.setState({ posts })
  }

  render() {
    return (
      <div>
        <form>
          {this.state.posts.map((p, i) => {
            return (
              <div>
                <label>{p.name}</label>
                <input type="checkbox" key={i} checked={p.selected} onClick={this.handleClick(i)} />
              </div>
            )
          })}
        </form>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

工作示例here