setState 不更新状态对象

setState not updating the state object

我正在从全栈反应这本书中学习反应。在其中一个示例投票应用程序中,您有产品和一个为产品投票的按钮。该按钮应该增加该产品的投票数,我将投票数存储在组件父级的状态中,并将其显示在子组件中。该投票功能无效。

我创建了父组件,它显示了显示产品描述、ID、颜色和投票(产品收到的投票数)的子组件

import React, { Component } from 'react';
import './App.css';
import Product from "./Product";

var products = [
  {
    id: 1,
    name: "one",
    color: "blue",
    votes:0
  },
  {
    id: 2,
    name: "two",
    color: "green",
    votes : 0
  },
  {
    id: 3,
    name: "three",
    color: "Red",
    votes : 1
  }
];

class App extends Component {

  //this function will be passed to child component so the child can pass any data needed back to the parent using function argument.
  handleProductUpVote(productId) {
    console.log("Product #" + " " +productId + " was upvoted")
  };

  render() {
    const productComponents = products.map((product) => {
      return <Product
        key={"product-" + product.id}
        id={product.id}
        name={product.name}
        color={product.color}
        votes={product.votes}
        /*this is how we pass the function from parent to the child as a prop*/
        onVote={this.handleProductUpVote}
      />
    });
    return (
      <div className="App">
        {productComponents}
      </div>
    );
  }
}

export default App;

这是我的子组件,它在其中呈现产品详细信息

import React, { Component } from 'react';

class Product extends Component {
  constructor(props) {
    super(props);
    this.handleUpVote = this.handleUpVote.bind(this);
  }

  //using the function passed from parent in a child. We pass any data needed back to parent component using parent's function arugments 
  // invoke this function using onClick event inside the button 
  handleUpVote() {
    this.props.onVote(this.props.id);
  };

  render() {
    return (
      <div>
        <p> name: {this.props.name} </p>
        <p> MYcolor: {this.props.color} </p>
        {/*invoke the function using onClick so it will invoke handleUpVote that will update the prop and pass the data back to parent*/}
        <button onClick={this.handleUpVote}> Upvote Me </button>
        <p>{this.props.votes}</p>
        <hr></hr>
      </div>
    )
  }
};

export default Product;

这是有效的,我在按下按钮时将消息记录到控制台 "Upvoteme"

但是当我尝试将设置移动到使用状态时。它不起作用 这是具有状态和 setState 的父组件。当我点击投票按钮时,投票计数没有任何变化。

import React, { Component } from 'react';
import './App.css';
import Child from "./Child";

var productseed = [
  {
    id: 1,
    name: "one",
    color: "blue",
    votes: 0
  },
  {
    id: 2,
    name: "two",
    color: "green",
    votes : 0
  },
  {
    id: 3,
    name: "three",
    color: "Red",
    votes : 1
  }
];

class Parent extends Component {
  constructor(props) {
    super(props);

    this.state = {
        products: [],
    };

    this.handleProductUpVote = this.handleProductUpVote.bind(this);
  }

  componentDidMount() {
    this.setState ({ products: productseed });
  }

  //this function will be passed to child component so the child can pass any data needed back to the parent using function argument.
  handleProductUpVote(productId) {
    // updating the vote in state
    const nextProducts = this.state.products.map((product) => {
      if (product.id === productId) {
        return Object.assign({}, product, {
          votes: product.votes + 1,
        });
      } else {
        return product
      }
    });

    this.setState({
      products: nextProducts,
    });
  }

  render() {
    const productComponents = productseed.map((product) => {
      return <Child
        key={"product-" + product.id}
        id={product.id}
        name={product.name}
        color={product.color}
        votes={product.votes}
        /*this is how we pass the function from parent to the child as a prop*/
        onVote={this.handleProductUpVote}
      />
    });

    return (
      <div className="App">
        parent
        {productComponents}
      </div>
    );
  }
}

export default Parent;

下一行假设指向该州的产品,但当我突出显示它时,它没有突出显示 this.state 中的产品。

控制台日志正在将消息记录到我的开发者控制台。这就是问题所在,this.setState 中的产品未指向 this.state.products,因此未更新状态。

componentDidMount() {
  this.setState({ products: productseed });
  console.log("this products not pointing to the this.state.products, why?")
}   

我阅读了有关 setState not working 的所有关于 Whosebug 的问题,但我遇到了同样的问题。如果您是有反应的专家并且能够看一下这个并找出问题出在哪里,我将不胜感激。我无法弄清楚我何时分配 this.setState({products: productseed}) 并且它不会更新状态。我花了近4个小时阅读和研究,请帮助。

您的问题出在 Parent 组件的 render 方法上。您正在遍历 productseeds 数组而不是您的状态。由于您正在更新状态而不是种子数组,因此 React 认为没有理由重新渲染任何内容,因此没有任何变化。

因此,如果您从

更改该行
const productComponents = productseed.map((product) => {...

const productComponents = this.state.products.map((product) => {...

你应该没事的。

另外关于你的:

The line below suppose to point to the products in the state but when I highlight it, it doesn't highlight the products in the this.state.

这只是与您正在使用的 IDE 相关的内容,与 React 无关。您正在传递一个具有属性的对象,并且大多数 IDE(或所有(?))不将 this.setState 的组合连接到状态对象。