setState()之后,更新后的状态不作为道具传递给组件

时间:2019-04-26 06:24:03

标签: javascript reactjs

我有一个名为'App'的主要React组件,其中包含处于其状态的用户输入数据。每次用户输入新数据时,都会使用setState()更新状态。然后将状态作为道具传递给另一个名为“ IncomeList”的组件,该组件将数据呈现在屏幕上。但是,在用户输入一些数据后,IncomeList组件不会获得更新状态。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.addData = this.addData.bind(this);
    this.state = {
      expenses: [],
      income: [],
    }
  }

  addData(data) {
    if (data.type == 'income')  {
      this.setState((prevState) => {
        income: prevState.income.push(data);
      }, console.log(this.state.income));
    } else if (data.type == 'expense') {
      this.setState((prevState) => {
        expenses: prevState.expenses.push(data);
      })
    }
  }

  render() {
    return (
      <div>
        <UserInput addData={this.addData} />
        <IncomeList income={this.state.income} />
      </div>
    );
  }
}
// UserInput component which contain a form
class UserInput extends React.Component {
  constructor(props) {
    super(props);
    this.addDataLocal = this.addDataLocal.bind(this);
  }

  addDataLocal(e) {
    e.preventDefault();
    const data = {
      type: e.target.elements.type.value,
      description: e.target.elements.description.value,
      amount: e.target.elements.amount.value 
    }
    this.props.addData(data);
  }

  render() {
    return (
      <div>
        <form onSubmit={this.addDataLocal}>
        <select name="type" id="input-type" name="type">
          <option value="income">Income</option>
          <option value="expense">Expense</option>
        </select>
        <input type="text" placeholder="decription..." name="description"/>
        <input type="number" placeholder="amount..." name="amount"/>
        <input type="submit" value="Add"/>
        </form>
      </div>
    )
  }
}

class IncomeList extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        {
          this.props.income.map((item) => {
            return (
              <IncomeListItem key={item.amount} item={item}/>
            )
          })
        }
      </div>
    )
  }
}

3 个答案:

答案 0 :(得分:2)

您不会从this.setState返回任何内容。您需要返回一个要与当前状态合并的对象。

addData(data) {
  const key = data.type === 'income' ? 'income' : 'expenses';

  this.setState(prevState => ({
    // with Computed Property Names we can make our
    // code concise and avoid conditionals
    [key]: [...prevState[key], data]
  }), console.log(this.state[key]));
}

答案 1 :(得分:0)

您的addData应该是这样

addData(data) {
if (data.type == 'income')  {
    let income=[...this.state.income];
    income.push(data);
    this.setState({
        income:income
    })
} else if (data.type == 'expense') {
    let expenses=[...this.state.expenses];
    expenses.push(data);
    this.setState({
        expenses:expenses
    });
}
 }

答案 2 :(得分:0)

With @Asaf Aviv input I have created a working fiddle. Hope this will help.

JS Fiddle