reactjs - 如何从子类中的componentdidmount将值返回到reactjs中的父类
问题描述
reactjs中如何从子类中的componentdidmount返回值到父类。单击 CARD 之一时,使用 PROMISE.all 从后端检索数据并保存在数据对象内部的子状态中。然后我需要一种方法将其返回给父类。当我阅读更多但没有输出时,我正在尝试不同的方式......
家长:
render() {
const { data} = this.state;
callbackFunction = (data) => {
this.setState({threeDaysData: data.getONE});
this.setState({fourteenDaysData: data.getTWO});
}
return (
<Grid container justify="center" alignItems="center" spacing={2}>
{
<Grid item xs={12} md={6} key={uj.userJourney}>
<Child2 title={`CLICK 2`}
threeDaysData
fourteenDaysData
// PASS threeDaysData and fourteenDaysData retrieved from to Child1 to Child2 ( on 2nd click )
/>
</Grid>
:
<Grid item xs={6}>
<Child1
title={`CLICK 1`}
// RETRIEVE OBJECT VALUE FROM CHILD 1 IN THIS PARAM
triggerParentUpdate={this.CallbackFunction(data)}
/>
</Grid>
}
</Grid>
);
}
Child1:
class Child1 extends Component {
state = {
3days: {
threeDaysData: 'No Data',
},
14days: {
fourteenDaysData: 'No Data',
}
data: {
threeDaysData: 'No Data',
fourteenDaysData: 'No Data'
}
};
render() {
const { title, data } = this.props;
const { last3days, last14days } = this.state;
return (
<Card>
<CardContent>
<Grid container>
{last3days !== undefined && last3days.calcThree !== undefined ? (
last3days.calcThree
.map((element) => {
return (
<Grid item xs={3}>
---
</Grid>
);
})
)}
{last14days !== undefined && last14days.calcThirty !== undefined ? (
last14days.calcThirty
.map((element) => {
return (
<Grid item xs={3}>
---
</Grid>
);
})
)}
</Grid>
</CardContent>
</Card>
);
}
componentDidMount() {
Promise.all([this.getData(3), this.getData(14)]).then((res) => {
this.setState({
3days: {
threeDaysData: res[0].data,
},
14days: {
fourteenDaysData: res[1].data,
}
data: {
threeDaysData: res[0].data,
fourteenDaysData: res[1].data
}
});
});
}
}```
解决方案
React 有一个“从父母到孩子”的流程,反之亦然。因此,为了将数据放入Parent
组件中,您只需将数据移到componentDidMount
那里,获取数据并通过 props 将其传递给所有子组件。
推荐阅读
- telegram - 是否可以通过 Telegram Bot 将消息发送到特定的电话号码(不是 chat_id/用户名)?
- react-native - fetch 和 axios 在 PlaidLink 组件中不起作用,我该如何解决?
- swift - 从 Int 变量设置 SwiftUI 键盘快捷键
- reactjs - 如何将具有键和值对的新对象添加到基于类的组件中的现有状态?
- python - 在某个单词之后查找两个字符串之间的字符串
- python - Tornado 测试 - 通过替代 IP 访问 localhost
- plugins - 为什么我收到错误消息,说 Plugins.yml 文件不存在?
- asp.net - MembershipCreateStatus.Success 的奇怪行为
- forms - 制作自定义 Yesod 表单:无法推断(Monad (FormInput m))
- powershell - 不需要 PowerShell 复制项文件夹结构