javascript - 如何在孩子的 componentDidMount 反应中从父级设置变量?
问题描述
我正在尝试从子组件中的 Api 请求中获取信息。问题是我面临访问父母的道具。更准确地说,如何获取父级的道具并将其设置在 componentDidMount() 中?父组件
class Parent extends Component {
constructor(){
super()
}
...
<Child id={id}/>
...
export default Parent;
子组件
class Child extends Component {
constructor(){
super()
this.state = {
id:'',
}
}
// I need somehow set parent's "id" inside the url
componentDidMount() {
const url = `https://api.../${id}?api_key=${apiKey}`;
axios.get( url )
...
};
render(){
const { id } = this.props;
console.log('Child id ' + id) // here I see all ids
return(
<div className="item" key={id}>
<p>{id}</p> // here as well
</div>
)
}
}
Child.propTypes = {
item: PropTypes.object
}
export default Child;
也许我在错误的地方寻找,我只需要改变逻辑。我将不胜感激任何建议
解决方案
要从 Child 组件中的任何位置访问 props,您需要将 props 传递给构造函数,然后您只需使用 this.props 访问它。
这应该有效:
class Child extends Component {
constructor(props){
super(props)
this.state = {},
}
componentDidMount() {
const id = this.props.id
const url = "https://api.../$" + id + "?api_key=${apiKey}";
axios.get( url )
...
};
}
推荐阅读
- c - 服务器套接字第一次没有收到消息。为什么会这样?
- c# - 从富文本框中的特定文本中查找并显示多行
- excel - 检查 CSV 文件是否为空或不使用 vba
- spring-boot - Spring Rest 控制器返回 404 未找到 POST 方法调用
- c# - 什么是 C# 全模拟 PHP 函数“similar_text()”?
- react-native - React Native FlatList 项目可以溢出容器吗?
- javascript - 表体内的 event.target 给出了错误的上下文,自定义上下文菜单的 div 重叠
- c# - 如何检查异步任务是否为空
- c++ - 如何使用 struct 将这些代码更改为 C++ 中的类?
- reactjs - 无法使用 create-react-app 设置反应