在基于React Class的组件中,将道具从父母传递给孩子

问题描述 投票:0回答:2

我是新来的反应者,因此无法弄清楚如何将从服务器接收的数据从父组件传递给子组件:

//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”:{}}

javascript reactjs axios
2个回答
0
投票

在您的子组件中,您需要以this.state.data.name而不是this.state.data的身份访问状态:

 <Form.Control type="text" value={this.state.data.name} disabled />

0
投票

您忘记了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 />
© www.soinside.com 2019 - 2024. All rights reserved.