简体   繁体   中英

Why use props in react if you could always use state data?

I understand that there's two ways to pass components data: props and state. But why would one need a prop over a state? It seems like the state object could just be used inside the component, so why pass the prop parameters in markup?

Props are set externally by a parent component. Eg;

render() {
    return <ChildComponent someProp={someValue}/>;
}

State is set internally, and often triggered by an user event within a child. Eg;

handleUserClickedButton: () {
    this.setState({
        buttonClicked: true
    });
},

render() {
    return <button onClick={this.handleUserClickedButton}/>;
}

So, props are a way for data to go from parent to child. State is a way for data to be managed within a singular component, and possibly have changes to that data triggered by children. In effect, they represent data traveling in 2 opposite directions, and the way in which they are passed is entirely unique.

There are two ways to "pass" or access data from outside your component but state is not one of them.
The two ways are:
Props - which a parent component pass down to the child component.
Context - which you can "skip" the direct parent in the tree.

The state is an internal object which no other component has access to it unless you pass it explicitly (via the two ways mentioned above).

So basically your question is not accurate as you can't really compare the two.
I think what you are really asking is why using a state-less instead of a state-full component.
Which you can find an answer here in Stack-overflow or in other websites.

Edit
A followup to some of your comments.

why does the child not just have a shared state? for example, each component (or sub-component) could just do a "this.state" to get the current state of the program

  1. The same way you can't share or access private objects in other functions.
  2. This is by design, you share things explicitly and you will pass only what the component needs. For example, look it this page of stack-overflow, lets say the voting buttons are components, why would i pass them the whole state if it only needs the vote count and 2 onClick event listeners? Should i pass the current logged in user or maybe the entire answers rendered in this page?

so you can't pass state between a parent to child? for example, can't the parent change the state and then the child gets the new state

This is exactly what the props or context should do, provide an API for sharing data between parents and children though we keep it in a one way data flow, from parents to children, you can't pass props upwards. but you invoke handlers passed down to your child components and pass data through that handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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