简体   繁体   English

在基于反应类的组件中将道具从父级传递给子级

[英]passing props from parent to child in react class based component

I am new to react and cannot figure out how to pass data received from the server from a parent component to a child component as such:我是新手,无法弄清楚如何将从服务器接收到的数据从父组件传递到子组件:

//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"/>
        );
    }

In my child component:在我的子组件中:

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 />
);
}

the input value comes out as empty object: {"name":{}}输入值作为空对象出现:{"name":{}}

I'd try to stay away from storing props inside of state so that your parent and children components don't get out of sync.我会尽量避免在state存储props ,这样你的parent组件和children组件就不会不同步。 Instead, use what you need from the props inside of children and then if you need to store some other information based on the props that are passed, use state for that.取而代之的是,使用您需要从children内部的props获取的信息,然后如果您需要根据传递的props存储一些其他信息,请使用state

Here's an example:下面是一个例子:

 class AlumniComponent extends React.Component { state = { profile: {}, isLoading: true, error: false }; componentDidMount() { fetch("https://jsonplaceholder.typicode.com/users/1") .then(res => res.json()) .then(data => { this.setState({ profile: data, isLoading: false }); }) .catch(error => { this.setState({ error: error.message, isLoading: false }); }); } render() { const { profile, isLoading, error } = this.state; if (isLoading) { return `Loading`; } if (!isLoading && error) { return `Something went wrong`; } return <AboutComponent data={profile} />; } } class AboutComponent extends React.Component { constructor(props) { super(props); const initialState = { name: this.props.data.name, selectedOption: null } this.state = { ...initialState } } handleChange = event => { this.setState({ name: event.target.value }); }; render() { const { name } = this.state; return <input type="text" value={name} onChange={this.handleChange} />; } } function App() { return ( <div className="App"> <AlumniComponent /> </div> ); } ReactDOM.render( <App />, document.getElementById("app") )
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>

Also, I don't know what the <Form.Control /> component is expecting for the value property, but make sure you grab the right information that you need instead of passing the entire prop/object into it.此外,我不知道<Form.Control />组件对value属性的期望,但请确保获取所需的正确信息,而不是将整个道具/对象传递给它。

class AboutComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      name: this.props.data.name
    }
  }

  handleChange = (event) => {
    this.setState({
      name: event.target.name
    })
  }

  render() {
    return (
      <Form.Control 
        type="text" 
        value={this.state.name} 
        onChange={this.handleChange}
        disabled 
      />
    )
  }
}

You forgot this this.props.data but this an anti pattern你忘了this.props.data但这种反模式

 this.state = {
  data: {
    name: this.props.data,
  },
};

You should do it in componentDidMount()您应该在componentDidMount()

componentDidMount(){
  this.setState({name:this.props.data.name})
}

Then:然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM