简体   繁体   English

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

[英]Updated state is not passed as props to component after setState()

I have a main react component called 'App' which contain user input data in its state. 我有一个名为“ App”的主要React组件,其中包含处于其状态的用户输入数据。 The state is updated with setState() every time user enter new data. 每次用户输入新数据时,都会使用setState()更新状态。 Then the state is passed as props to another component called 'IncomeList' which render the data on screen. 然后将状态作为道具传递给另一个名为“ IncomeList”的组件,该组件将数据呈现在屏幕上。 However the IncomeList component is not getting updated state after user input some data. 但是,在用户输入一些数据后,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>
    )
  }
}

You don't return anything from this.setState . 您不会从this.setState返回任何this.setState You need return an object to be merged with your current state. 您需要返回一个要与当前状态合并的对象。

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]));
}

your addData should be like this 您的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
    });
}
 }
With @Asaf Aviv input I have created a working fiddle. Hope this will help.

JS小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 setState被在props中传递的方法中断,该方法设置了父组件的状态 - setState interrupted by a method passed in props which sets state of parent component ReactJS更新状态未实时传递给子组件 - ReactJS Updated state not passed in realtime as props to child component 父组件的 state 更新后,子组件中的道具未更新 - props not updating in child component after parent component's state is updated 将 .setState() 之后的状态传递给子组件,但未显示在子组件的 this.props 中 - Passing state after .setState() to child component but not showing up in this.props for child component 反应 function 组件的 setState 未更新我的 state - setState for react function component not updated my state ReactJS:setState和回调后状态未更新 - ReactJS: state not updated after setState and callback 反应组件状态不使用传递的道具更新 - React component state not updating with passed props 状态通过子组件中未定义的道具 - State passed through props undefined in child component React调用在无状态组件的props中传递的调用setState的函数 - React invoking function calling setState passed in props of a stateless component setState() 的异步性质不显示来自父组件的更新道具 - Async nature of setState() not showing updated props from parent component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM