javascript-映射对象数组并使用React中的onClick更改值

我正在尝试使用map()列出每个obj时更改cardArr对象内like的值.

下面是我的代码.
当前,它可以工作,但是每个对象共享同一个计数器,因为它不是从对象调用的.我了解我目前只是在调用状态中存储的对象属性,但是如何使用地图函数在每个对象中编辑类似对象?

import React, { Component } from 'react';

const cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]


export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
      like: 0,
      show: true
    };
     // this.handleClick = this.handleClick.bind(this);


  }



IncrementItem = () => {
    this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
    this.setState({ like: this.state.like - 1 });
}

// handleClick(e) {
//  e.preventDefault();
//  this.IncrementItem();
// }
// handleClick(e) {
//  e.preventDefault();
//  this.DecreaseItem();
// }


render() {

    const cardList = (cardArr.map((card) => 

        <ul>
            <li>
            <div key={card.id}>
                {card.text};
                <img src={card.img}/>
                <p>Like Button</p>
                <button onClick={this.handleClickAdd}>Like</button>
                <p>Dilike Button</p>
                <button onClick={this.DecreaseItem}>Disike</button>
                <p>Likes: {this.state.like}</p>
            </div>
            </li>
        </ul>
        ));

    return(
        <div id='card'>
            {cardList}
        </div>
    )
}
}

解决方法:

将cardArr移至组件状态,以便在每个onClick(喜欢或不喜欢)上都可以根据需要像prop一样进行更改:

const Card = ({ card, onLike, onDeslike }) =>
  <div>
    {card.text}
    <p>Likes: {card.like}</p>
    <button onClick={() => onLike(card.id)}>Like</button>
    <button onClick={() => onDeslike(card.id)}>Deslike</button>
  </div>

class CardList extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      cards: [
        {
          id: 1,
          text: 'Hey this is a test.',
          img: ' ',
          like: 0,
        },
        {
          id: 2,
          text: "If this works I'll call it a day.",
          img: ' ',
          like: 0,
        },
        {
          id: 3,
          text: "I'll drink a lot of beer.",
          img: ' ',
          like: 0,
        },
        {
          id: 4,
          text: 'Cheers',
          img: ' ',
          like: 0,
        },
      ]
    }

    this.handleLike = this.handleLike.bind(this)
    this.handleDeslike = this.handleDeslike.bind(this)
  }

  handleLike(id) {
    this.setState(prevState => ({
      ...prevState,
      cards: prevState.cards.map(card => ({
        ...card,
        like: card.id === id ? card.like + 1 : card.like
      }))
    }))
  }

  handleDeslike(id) {
    this.setState(prevState => ({
      ...prevState,
      cards: prevState.cards.map(card => ({
        ...card,
        like: card.id === id ? card.like - 1 : card.like
     }))
    }))
  }

  render() {
    return (
      <div>
        <ul>
          {this.state.cards.map(card =>
            <li key={card.id}>
              <Card
                card={card}
                onLike={this.handleLike}
                onDeslike={this.handleDeslike}
              />
            </li>
          )}
        </ul>
      </div>
    )
  }
}

ReactDOM.render(
  <CardList />,
  document.getElementById('root')
)
<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>
<div id="root"></div>

不要忘记setState是异步的,因此,您不会马上拥有它的最新更改.

上一篇:javascript-如何解决异步函数中的承诺?


下一篇:javascript-将函数作为参数传递,这将是onClick事件