反应父组件对孩子的合计值不准确

时间:2018-06-24 08:24:37

标签: javascript reactjs parent-child state

嘿,我有一个可重用的列表组件,可以在其中添加项目并添加价格的总和,并且我希望将此组件包含在父组件中,在其中我拥有总和以及一个用于添加更多列表的按钮。 我如何获得款项? 到目前为止,我已经将它们添加到数组中,但是值不是应该的值。

代码:

import React from 'react';
import styled from 'styled-components';
import ShoppingList2 from './ShoppingList2';

const Container = styled.div `
  position:absolute;
  left:0;
  bottom:0;
  right:0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

class TotalPrice extends React.Component {
  state = {
    shoppingLists2: [ShoppingList2],
    shoplistsums: [],
    sum: 0
  }

  AddShoppingList = () => {
    let shoppingLists2 = this.state.shoppingLists2.concat(ShoppingList2);
    this.setState({
      shoppingLists2
    })
    console.log(this.state.shoppingLists2);
  }

  onUpdate = (val) => {
    console.log('val', val);
    let shoplistsums = this.state.shoplistsums.concat(val);
    console.log('shpl', shoplistsums);
    let sum = shoplistsums.reduce(function(a, b) {
      return a + b;
    });
    this.setState({
      shoplistsums,
      sum
    })
  }

  render() {
    return (
      <div>
        {this.state.shoppingLists2.map((shoppingList, index)=>(
          <ShoppingList2
            key={index}
            value={this.onUpdate}
          />
        ))}
        <Container>
          <label>Total:</label>
          <label>{this.state.sum + ' €'}</label>
          <button onClick={this.AddShoppingList}>Add Receipt</button>
        </Container>
      </div>
    );
  }
}

export default TotalPrice;

子组件

import React from 'react';
import styled from 'styled-components';
import InputFields from './InputFields';

const Container = styled.div `
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

class ShoppingList extends React.Component {

  state = {
    questions: [''],
    sum: 0
  }

  handleText = i => e => {
    let questions = [...this.state.questions];
    questions[i] = parseInt(e.target.value);
    if (questions.length === 1 && isNaN(questions[0])) {
      questions[0] = ''
    }
    let sum = questions.reduce(function(a, b) {
      if (isNaN(a)) {
        a = '';
      }
      if (isNaN(b)) {
        b = '';
      }
      return a + b;
    });
    console.log('sum', sum);
    this.props.value(sum);
    this.setState({
      questions,
      sum
    })
  }

  addExpense = e => {
    e.preventDefault()
    let questions = this.state.questions.concat([''])
    this.setState({
      questions
    })
  }

  render() {
    return (
      <div>
        <Container>
          <select>
            <option value="food">Food</option>
            <option value="houseware">Houseware</option>
            <option value="entertainment">Entertainment</option>
          </select>
          <button onClick={this.addExpense}>Add expense</button>
        </Container>
        {this.state.questions.map((question, index) => (
          <Container  key={index}>
            <input
              type="text"
            />
            <input
              type="number"
              onChange={this.handleText(index)}
              value={question}

            />
          </Container>
        ))}
        <Container>
          <label>Total:</label>
          <label>{this.state.sum ? this.state.sum + ' €' : 0 + ' €'}</label>
        </Container>
      </div>
    )
  }
}

export default ShoppingList;

1 个答案:

答案 0 :(得分:0)

{this.state.shoppingLists2.map((shoppingList, index)=>(
  <ShoppingList2
    key={index}
    value={this.onUpdate}
  />
 ))}

在这里,您正在使用多个购物清单组件,但仅呈现已导入的组件。代替这个

{this.state.shoppingLists2.map((ShoppingList, index)=>(
  <ShoppingList
    key={index}
    value={this.onUpdate}
  />
 ))}

下一个问题是您正在从子组件中发送值(总和)。然后对总和求和,当您应该根据自己的代码求和单个数字时。

我修改了您的代码。并根据组件的索引存储值(和)。最后将它们总结为

这是完整的组件

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import ShoppingList2 from "./ShoppingList2";

const Container = styled.div`
  position: absolute;
  left: 0;
  bottom: 0;
  right: 0;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

class TotalPrice extends React.Component {
  state = {
    shoppingLists2: [ShoppingList2],
    shoplistsums: {},
    sum: 0
  };

  AddShoppingList = () => {
    let shoppingLists2 = this.state.shoppingLists2.concat(ShoppingList2);
    this.setState({
      shoppingLists2
    });
    console.log(this.state.shoppingLists2);
  };

  onUpdate = index => val => { // changed here
    console.log("val", val);
    let shoplistsums = { // and here
      ...this.state.shoplistsums,
      [index]: val
    };
    console.log("shpl", shoplistsums);
    // and this block, using reduce would do as well, but I like this method better
    let sum = 0; 
    Object.keys(shoplistsums).forEach(key => {
      sum += shoplistsums[key];
    });
    this.setState({
      shoplistsums,
      sum
    });
  };

  render() {
    return (
      <div>
        {this.state.shoppingLists2.map((ShoppingList, index) => (
          <ShoppingList key={index} value={this.onUpdate(index)} /> /* changed here */
        ))}
        <Container>
          <label>Total:</label>
          <label>{this.state.sum + " €"}</label>
          <button onClick={this.AddShoppingList}>Add Receipt</button>
        </Container>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<TotalPrice />, rootElement);