【问题标题】:React displaying sum of child components values not accurate反应显示子组件值的总和不准确
【发布时间】:2018-12-03 03:57:16
【问题描述】:

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

代码:

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;

这是它的外观和工作原理以及问题:

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

【问题讨论】:

  • 看起来 questions 是一个字符串数组。你如何通过添加一个字符串数组来得到总和?如果问题处于具有问题(字符串)和值(数字)的对象的状态下,那么对于 sum 添加应用程序值(数字)会更好。
  • 问题[i] = parseInt(e.target.value);它在 ShoppingList 中解析
  • 你的设计中应该有什么问题。美食、家居娱乐?还是它们是类别?

标签: javascript arrays reactjs components


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2020-12-26
    • 2021-11-22
    • 2018-06-09
    • 1970-01-01
    • 2020-10-19
    相关资源
    最近更新 更多