![](/img/trans.png)
[英]How do you update state in parent component from a child component when an event takes place in the parent component
[英]How Do You Change Parent Component' State From Child Component?
我想做的事
在我的第一个组件中,我得到状态为 2 的项目并将它们放入复选框。
在我的第二个组件中,我将项目的状态更改为 3。
我是第三个组件,在第二个组件中更改状态后,模态打开。
当 Modal 关闭时,导航会返回到第一个组件。
问题是我更改其状态的项目仍在第一个组件中。
他们的状态是 3,所以他们不应该在第一个组件中。
在这种情况下,你如何解决这个问题?
看起来,componentDidUpdate 在这里不起作用。
如果您能给我任何建议,我将不胜感激。
当前代码
第一个组件
export default class fist extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
checkedItems: [],
};
}
onUpdate = (item) => {
this.setState((previous) => {
const { checkedItems } = previous;
const index = checkedItems.indexOf(item);
if (index === -1) {
checkedItems.push(item);
} else {
checkedItems.splice(index, 1);
}
return { checkedItems };
});
};
async componentDidMount() {
const items = db.itemsCollection
.where('status', '==', 2)
.get();
this.setState({ items });
}
render() {
const { items, checkedItems } = this.state;
return (
<Container>
<View style={styles.list_asset}>
{items.map((item) => (
<View style={styles.article_asset} key={item.id}>
<Text style={styles.phrase}>{item.name}</Text>
<View style={styles.area_price}>
<CheckBox
style={styles.check}
checked={!!checkedItems.find((obj) => obj == item)}
onPress={() => this.onUpdate(item)}
/>
</View>
</View>
))}
</View>
</Container>
);
}
}
第二部分
updateItemsStatus = (id) => {
this.itemsCollection.doc(id).update({
status: 3,
updated_at: new Date(),
});
return true;
}
第三部分
<TouchableOpacity
onPress={() => {this.props.navigation.navigate('first component')}}
>
<Text>Close Modal</Text>
</TouchableOpacity>
如果我理解,您的问题是模式关闭后您的数据没有刷新。
那是因为您在触发一次的ComponentDidmount()
中获取数据,然后直接更新数据库。
在您的第二个组件中,您可以从您的父级传递一个方法,该方法将更新您的 state。 这是一个通用示例:
class App extends React.Component {
state = {...items};
updateState = (newStatus) => {
this.setState(prevState => ({...prevState, status:newStatus}));
// or get data again from your db (careful about async)
};
render() {
return (
<Child updateState={updateState} />
)
}
}
class Child extends React.Component {
render(){
return <TouchableOpacity onPress={() => this.props.updateState(3)}>Touch me daddy</TouchableOpacity>
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.