首页 > 解决方案 > 为什么我不能在 reactjs 类组件中使用两种状态?

问题描述

 class Pumashoe01 extends Component {
  state = {
    products: [
      {
        "_id": "1",
        "title": "Puma Shoes",
        "src": [
          "https:h_1440,q_90,w_1080/v1/assets/images/11335328/2020/5/21/63e51b29-0e3d-4e0e-a9c5-6f2c34720ef41590079916986PumaMenNavyBlueGreenLevelIDPSneakers4.jpg",
       
        ],
        "description": "Men Black Flex Fire V1 IDP Sneakers",
        "content": " A pair of round-toe black sneakers, has regular styling, lace-up detail Textile upper Cushioned footbed Textured and patterned outsole.",
        "price": 2364,
      }
    ],
    index: 0
  };
  myRef = React.createRef();

  handleTab = index => {
    this.setState ({ index: index })
    const images = this.myRef.current.children;
    for (let i = 0; i < images.length; i++) {
      images[i].className = images[i].className.replace("active", "");
    }
    images[index].className = "active";
  };

  componentDidMount() {
    const { index } = this.state;
    this.myRef.current.children[index].className = "active";
  }

  constructor(props) {
    super(props);
    this.state = {count: 0 }
    this.increment = this.increment.bind(this)
  }

  increment() {
this.setState( {count:this.state.count + 1},
  () => {
console.log('callback value', this.state.count)})
console.log(this.state.count)}



  render() {
    const { products, index } = this.state;
 return (
  {
          products.map(item => (

            <div className="details" key={item._id}>
              <div className="big-img">
                <img src={item.src[index]} alt="" />
              </div>
              <div className="box">
                <div className="row">
                  <h2>{item.title}</h2>
                  <span>₹{item.price}</span>
                </div>


                <p>{item.description}</p>
                <p>{item.content}</p>
              
                <DetailsThumb images={item.src} tab={this.handleTab} myRef={this.myRef} />

                <p>You clicked {this.state.count } times</p>

                   <button onClick={this.increment}  className="cart">Add to cart</button>

                   
                <button   className="Buynow">Buy Now</button>
              </div>
            </div>
          ))
        }
      </div>
    );
  };
}

为什么我不能在一个类组件中使用两个具有相同拼写的状态。如果我两次设置相同的状态拼写,则显示地图未定义错误。如果我在构造函数中更改状态拼写,其功能将不起作用。帮我解决这个问题,为什么我不在 reactjs 的单个类组件中使用两种不同的功能状态。

标签: reactjsreact-reduxmaterial-ui

解决方案


推荐阅读