我是新来的反应者,因此无法弄清楚如何将从服务器接收的数据从父组件传递给子组件:
//parent component
class AlumniComponent extends React.Component {
state = {
profile : {},
error: false
}
componentDidMount(){
Axios.get('https://jsonplaceholder.typicode.com/users/1')
.then(response=>{
// console.log(response.data);
this.setState({profile: response.data})
})
.catch(error=>{
console.log(error);
this.setState({error: true})
})
}
render() {
const profile = this.state.profile;
return(
<AboutComponent data={profile} tab="about"/>
);
}
在我的子组件中:
class AboutComponent extends React.Component {
constructor(props){
super(props);
this.state = {
data: {
name: props.data // <--- the props are coming coming from the parent component !?
},
selectedOption: null,
};
}
render (){
return (
<Form.Control type="text" value={JSON.stringify(this.state.data)} disabled />
);
}
输入值作为空对象出现:{“ name”:{}}
在您的子组件中,您需要以this.state.data.name
而不是this.state.data
的身份访问状态:
<Form.Control type="text" value={this.state.data.name} disabled />
您忘记了this this.props.data
,但这是一个反模式
this.state = {
data: {
name: this.props.data,
},
};
您应该在componentDidMount()
中进行
componentDidMount(){
this.setState({name:this.props.data.name})
}
然后:
<Form.Control type="text" value={this.state.name} disabled />