【发布时间】:2017-01-11 14:07:50
【问题描述】:
如何使用 setState [child to parent] 重新渲染数据? FoodList 中的 deleteItem 函数应删除所选数据并重新渲染。我不是要求删除代码,而是我将如何重新渲染在子组件中具有函数的主组件,该子组件应该 deleteItem 进行重新渲染
我有 3 个组件。 Main、Food 和 FoodList。
主组件 - 通过状态保存数组中的食物列表并将其作为道具传递给食物组件。
class Main extends Component{
constructor(){
super();
this.state = {
foods: []
};
}
componentWillMount(){
this.setState({
foods: [
{
id: uui.v4(),
name: "Chocolate Cake",
category: "dessert"
},
{
id: uui.v4(),
name: "Milkshake",
category: "beverage"
}
]
});
}
render(){
return(<Food lists={this.state.foods}/>);
}
}
食物组件 - 映射接收到的食物列表道具并将其传递给 FoodList 组件以呈现为 lis
class Food extends Component{
render(){
let items;
//check if object has value;
if(this.props.lists)
{
items = this.props.lists.map(food => {
//pass each food as props
return <FoodList key={food.id} food_list={food} />;
});
}
return(
<div>
<h3>Available Foods</h3>
{items}
</div>
);
}
}
FoodList 组件 - 接收映射的道具并渲染为 li
class FoodList extends Component {
deleteItem(id)
{
console.log(id);
//delete item using passed id and re rende food state in Main Component
}
render(){
return <li>{this.props.food_list.name} - {this.props.food_list.category}
<a href="#" onClick={this.deleteItem.bind(this, this.props.food_list.id)}>Delete</a>
</li>
}
}
【问题讨论】:
-
旁注,您可以在构造函数中设置状态并摆脱 componentWillMount
-
先生,我正在关注 youtube 上的教程,他更喜欢 componentWillMount() 吗?你认为先生是最好的选择?
-
如果您已经拥有数据(您拥有),那么我会将其分配给构造函数中的状态。您已经在分配食物:[],然后在 componentWillMount 中再次分配。您可以在构造函数中完成所有操作
标签: javascript reactjs