为什么子组件不更新?

时间:2018-08-15 13:45:19

标签: reactjs state rerender

当我更改产品名称时(在第一个情况下),我可以从App-> List跟踪更改。但是list_item没有更新其道具。我认为问题在于该组件没有重新渲染,而是重新渲染。这些道具没有更新,我也不知道为什么。

app.js

import React, { Component } from 'react';

import List from './list';

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

    this.state = {
      products: [
        {
          name: 'TV',
          price: 1000,
          currency: 'USD'
        },
        {
          name: 'SSD',
          price: 100,
          currency: 'USD'
        }
      ],

      name: '',
      price: '',
      currency: ''
    };
  }

  handleChange = event => {
    console.log(`${event.target.name}: ${event.target.value}`);
    this.setState({ [event.target.name]: event.target.value });
  };

  changeState = e => {
    e.preventDefault();
    let products = [...this.state.products];
    products[0].name = this.state.name;
    products[0].price = this.state.price;
    products[0].currency = this.state.currency;

    this.setState({
      products
    });
  };

  render() {
    return (
      <div>
        <button onClick={() => console.log(this.state)}>log</button>
        <List products={this.state.products} />

        <p>{this.state.products[0].name}</p>

        <form onSubmit={this.changeState}>
          Name:
          <br />
          <input
            type="text"
            name="name"
            // defaultValue={this.state.product.name}
            onChange={this.handleChange}
          />
          <br />

          // for simplicity I'm skipping price and currency 
          // but they are there

          <input type="submit" value="Update" />
        </form>
      </div>
    );
  }
}

export default App;

list.js

import React, { Component } from 'react';
import ListItem from './list_item';

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

    this.state = props;
  }

  render() {
    const productItems = this.state.products.map((product, i) => {
      console.log(product.name);
      return (
        <ListItem
          key={i}
          id={i}
          name={product.name}
          price={product.price}
          currency={product.currency}
        />
      );
    });
    return (
      <table>
        <tbody>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Price</th>
            <th>Currency</th>
            <th>Permissions</th>
          </tr>
          {productItems}
        </tbody>
      </table>
    );
  }
}

export default List;

list_item.js

import React, { Component } from 'react';

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

    this.state = props;
  }

  render() {
    console.log(this.state);
    console.log('rendering');
    return (
      <tr>
        <td>{this.state.id}</td>
        <td>{this.state.name}</td>
        <td>{this.state.price}</td>
        <td>{this.state.currency}</td>
      </tr>
    );
  }
}

export default ListItem;

1 个答案:

答案 0 :(得分:1)

list_item.js中遇到的问题是构造函数中的this.state = props。构造函数仅调用一次,因此在初始化组件时就定义了状态,但从未更新过。

您实际上不需要此组件中的状态:

<tr>
        <td>{this.props.id}</td>
        <td>{this.props.name}</td>
        <td>{this.props.price}</td>
        <td>{this.props.currency}</td>
      </tr>

由于不需要状态,因此可以使用无状态组件:

const ListItem = ({id, name, price, currency}) => (
  <tr>
    <td>{id}</td>
    <td>{name}</td>
    <td>{price}</td>
    <td>{currency}</td>
  </tr>
);

顺便说一句,您在list.js中也遇到了同样的问题,也可能是无状态组件。

如果您需要通过道具更新您的当地状态,则应该看看getDerivedStateFromPropscomponentDidUpdate

但是在您的情况下,您不需要这样做。