我试图将一个参数从父组件传递给子组件的ComponentDidMount()方法。我只能在子组件的render()内接收道具,我无法将其传递给ComponentDidMount()方法。
父组件 - Provider.js
export default class Provider extends Component {
constructor(props) {
super(props);
this.state = {
carePlan: "",
patID: ""
};
}
async componentDidMount() {
this.setState({
carePlan: this.cp
patID: this.props.location.state.id
});
console.log(this.state.patID);
}
render() {
return (
<div>
<Layout>
{!this.state.cp ? (
<AddCarePlan patID={this.state.patID} />
) : (
<div className="carePlan">
<DisplayCarePlan cp={this.state.carePlan} />
</div>
)}
</Content>
</Layout>
</div>
);
}
}
子组件 - AddCarePlan.js
class AddCarePlan extends Component {
constructor(props) {
super(props);
}
async componentDidMount() {
const patientID = this.props.patID;
console.log(patientID) // does not show ID
}
render() {
const patientID = this.props.patID;
console.log(patientID) // shows ID
return (
<div>
<h1> Add Care Plan </h1>
</div>
);
}
}
export default AddCarePlan;
您应该在组件中的生命周期方法之前删除关键字异步。正如我可以告诉你的那样,他们并没有在其中使用等待而且+ React并不是设计用于async await函数。即使您想使用componentDidMount进行一些数据提取,也不应该使用async,因为当数据到达时,数据提取的()方法将触发组件重新呈现。
尝试从代码中删除异步。
试试这个怎么样?
{!this.state.cp ? (
this.state.patID ? <AddCarePlan patID={this.state.patID} /> : ''
) : (
<div className="carePlan">
<DisplayCarePlan cp={this.state.carePlan} />
</div>
)}
export default class Provider extends Component {
constructor(props) {
super(props);
this.state = {
carePlan: "",
patID: props.location.state.id
};
}
async componentDidMount() {
this.setState({
carePlan: this.cp
});
console.log(this.state.patID);
}
render() {
return (
<div>
<Layout>
{!this.state.cp ? (
<AddCarePlan patID={this.state.patID} />
) : (
<div className="carePlan">
<DisplayCarePlan cp={this.state.carePlan} />
</div>
)}
</Content>
</Layout>
</div>
);
}
}
试试这种方式
this.state = {
carePlan: "",
patID: ""
};
async componentWillMount() {
this.setState({
patID: this.props.location.state.id
});
}
或尝试改变生命周期