gpt4 book ai didi

javascript - 在 setState() 之后更新的状态不会作为 props 传递给组件

转载 作者:行者123 更新时间:2023-11-30 14:03:41 26 4
gpt4 key购买 nike

我有一个名为“App”的主要 React 组件,其中包含处于其状态的用户输入数据。每次用户输入新数据时,状态都会用 setState() 更新。然后状态作为 Prop 传递给另一个名为“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>
)
}
}

最佳答案

您不会从 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]));
}

关于javascript - 在 setState() 之后更新的状态不会作为 props 传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55861881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com