javascript - react 显示子组件值的总和不准确

标签 javascript arrays reactjs components

我试图显示所有子组件列表值的总和,但它不准确,因为它也将以前的值保留在数组中,我该如何解决这个问题?

代码:

import React from 'react';
import styled from 'styled-components';

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 => {
    console.log('id', this.state.id);
    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;

和:

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);
    console.log(shoppingLists2);
    this.setState({
      shoppingLists2
    })
  }

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

  render() {
    return (
      <div>
        {this.state.shoppingLists2.map((ShoppingList2, 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;

这是它的外观和工作方式以及问题所在:enter image description here

我最近才开始使用 React,所以如果您有其他建议,请告诉我!

最佳答案

已修复,您可以查看@ - https://github.com/benonymus/timetravel

关于javascript - react 显示子组件值的总和不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51008829/

相关文章:

c++ - 通用数组/指针数据类型

java - 返回盒子的数组

javascript - 更好地调试控制台输出以解决 React StatelessComponent 中的错误

reactjs - 让 Nextjs 忽略 babel.config.js

javascript - 如何只允许一个事件的 useState

javascript - 如何使用 jquery.live()

javascript - D3.js 可折叠树 - 展开/折叠中间节点

javascript - 使用 JS 循环中的值填充 HTML 表格

javascript - Vue2 导出 SVG 元素以作为文件下载

javascript - 将输入标签值传输到 JavaScript 函数