Javascript 如何在子';什么成分会起反应?
我正在尝试从子组件中的Api请求获取信息。问题是我遇到了访问家长道具的问题。更准确地说,如何获取家长的道具并将其设置在componentDidMount()中? 父组件Javascript 如何在子';什么成分会起反应?,javascript,reactjs,api,Javascript,Reactjs,Api,我正在尝试从子组件中的Api请求获取信息。问题是我遇到了访问家长道具的问题。更准确地说,如何获取家长的道具并将其设置在componentDidMount()中? 父组件 class Parent extends Component { constructor(){ super() } ... <Child id={id}/> ... export default Parent; class Child extends Component { construct
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;
类父级扩展组件{
构造函数(){
超级()
}
...
...
导出默认父对象;
子组件
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;
类子级扩展组件{
构造函数(){
超级()
this.state={
id:“”,
}
}
//我需要在url中设置家长的“id”
componentDidMount(){
常量url=`https://api.../${id}?api_key=${apiKey}`;
获取(url)
...
};
render(){
const{id}=this.props;
log('Child id'+id)//在这里我看到了所有的id
返回(
{id}//这里也是
)
}
}
Child.propTypes={
项目:PropTypes.object
}
导出默认子对象;
也许我找错地方了,我需要改变逻辑。
如果您在组件中有构造函数,我将非常感谢您的建议。应该始终将道具传递给构造函数,并使用super()对组件进行反应
在您的情况下,如果您必须使用您的父母道具,您也应该将父母道具传递给孩子,并且在构造函数中使用相同的语法,您可以使用在子组件的任何位置传递的道具,并且您可以在componentDidMount中设置该道具,以便从您需要传递道具的子组件中的任何位置访问道具,然后使用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 )
...
};
}
你也必须把父母的道具作为道具传递给孩子。