setState不更新状态对象

时间:2019-01-04 18:46:09

标签: reactjs setstate

我正在从全书本反应中学习反应。在其中一个示例投票应用程序中,您拥有产品和用于对该产品进行投票的按钮。该按钮应该增加该产品的投票数,我将投票数存储在组件“父状态”中,并将其显示在子组件中。该投票功能不起作用。

我创建了父组件,在其中显示子组件,这些子组件显示了产品说明,标识,颜色和投票(产品收到的投票数)

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不相关的关于stackoverflow的每个问题,但我遇到了同样的问题。如果您有反应并能够解决这个问题并弄清楚问题出在哪里,我将非常感激。我无法确定何时分配this.setState({products:productseed}),并且它不会更新状态。在过去的4个小时里,我几乎都在阅读和研究,请帮忙。

1 个答案:

答案 0 :(得分:3)

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

因此,如果您更改该行为

const productComponents = productseed.map((product) => {...

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

你应该没事的。

关于您的:

  

下面的行应该指向状态中的产品,但是当我突出显示它时,它并没有突出显示this.state中的产品。

这只是与您正在使用的IDE有关的内容,而没有关于react的具体说明。您正在传递具有属性的对象,并且大多数IDE(或所有(?))都不会将带有this.setState的组合连接到状态对象。

相关问题