Javascript React 中的 state 和 props 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27991366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:04:25  来源:igfitidea点击:

What is the difference between state and props in React?

javascriptreactjs

提问by skaterdav85

I was watching a Pluralsight course on React and the instructor stated that props should not be changed. I'm now reading an article (uberVU/react-guide)on props vs. state and it says

我正在观看关于 React 的 Pluralsight 课程,讲师说不应该更改道具。我现在正在阅读一篇关于 props vs. state的文章(uberVU/react-guide),它说

Both props and state changes trigger a render update.

props 和 state 更改都会触发渲染更新。

Later in the article it says:

文章后面说:

Props (short for properties) are a Component's configuration, its options if you may. They are received from above and immutable.

道具(属性的缩写)是一个组件的配置,如果可以的话,它的选项。它们是从上面接收的并且是不可变的。

  • So props can change but they should be immutable?
  • When should you use props and when should you use state?
  • If you have data that a React component needs, should it be passed through props or setup in the React component via getInitialState?
  • 那么 props 可以改变,但它们应该是不可变的?
  • 什么时候应该使用 props,什么时候应该使用 state?
  • 如果你有一个 React 组件需要的数据,它应该通过 props 传递还是通过 React 组件中的 setup getInitialState

回答by Todd

Props and state are related. The state of one component will often become the props of a child component. Props are passed to the child within the render method of the parent as the second argument to React.createElement()or, if you're using JSX, the more familiar tag attributes.

props 和 state 是相关的。一个组件的状态通常会成为子组件的道具。道具在父级的 render 方法中作为第二个参数传递给子级,React.createElement()或者,如果您使用的是 JSX,则是更熟悉的标记属性。

<MyChild name={this.state.childsName} />

The parent's state value of childsNamebecomes the child's this.props.name. From the child's perspective, the name prop is immutable. If it needs to be changed, the parent should just change its internal state:

父母的状态值childsName成为孩子的this.props.name。从孩子的角度来看,名称道具是不可变的。如果需要更改,父级应该只更改其内部状态:

this.setState({ childsName: 'New name' });

and React will propagate it to the child for you. A natural follow-on question is: what if the child needs to change its name prop? This is usually done through child events and parent callbacks. The child might expose an event called, for example, onNameChanged. The parent would then subscribe to the event by passing a callback handler.

React 会为你将它传播给孩子。一个自然的后续问题是:如果孩子需要更改其名称道具怎么办?这通常通过子事件和父回调来完成。孩子可能会公开一个名为的事件,例如,onNameChanged。然后,父级将通过传递回调处理程序来订阅该事件。

<MyChild name={this.state.childsName} onNameChanged={this.handleName} />

The child would pass its requested new name as an argument to the event callback by calling, e.g., this.props.onNameChanged('New name'), and the parent would use the name in the event handler to update its state.

子进程将通过调用例如 将其请求的新名称作为参数传递给事件回调this.props.onNameChanged('New name'),而父进程将在事件处理程序中使用该名称来更新其状态。

handleName: function(newName) {
   this.setState({ childsName: newName });
}

回答by BentOnCoding

For parent-child communication, simply pass props.

亲子交流,简单的传递道具。

Use stateto store the data your current page needs in your controller-view.

使用state将当前页面所需的数据存储在控制器视图中。

Use propsto pass data & event handlers down to your child components.

使用props将数据和事件处理程序传递给您的子组件。

These lists should help guide you when working with data in your components.

这些列表应该有助于指导您处理组件中的数据。

Props

道具

  • are immutable
    • which lets React do fast reference checks
  • are used to pass data down from your view-controller
    • your top level component
  • have better performance
    • use this to pass data to child components
  • 是不可变的
    • 这让 React 可以进行快速的参考检查
  • 用于从视图控制器向下传递数据
    • 你的顶级组件
  • 有更好的表现
    • 使用它来将数据传递给子组件

State

状态

  • should be managed in your view-controller
    • your top level component
  • is mutable
  • has worse performance
  • should not be accessed from child components
    • pass it down with props instead
  • 应该在您的视图控制器中管理
    • 你的顶级组件
  • 是可变的
  • 性能更差
  • 不应从子组件访问
    • 而是用道具传递下去

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event. Flux pattern is one of the possible ways to arrange this. - https://facebook.github.io/react/tips/communicate-between-components.html

What Components Should Have State?

Most of your components should simply take some data from props and render it. However, sometimes you need to respond to user input, a server request or the passage of time. For this you use state.

Try to keep as many of your components as possible stateless. By doing this you'll isolate the state to its most logical place and minimize redundancy, making it easier to reason about your application.

A common pattern is to create several statelesscomponents that just render data, and have a stateful component above them in the hierarchy that passes its state to its children via props. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way. - https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state

What Should Go in State?

State should contain data that a component's event handlers may change to trigger a UI update. In real apps this data tends to be very small and JSON-serializable. When building a stateful component, think about the minimal possible representation of its state, and only store those properties in this.state. Inside of render() simply compute any other information you need based on this state. You'll find that thinking about and writing applications in this way tends to lead to the most correct application, since adding redundant or computed values to state means that you need to explicitly keep them in sync rather than rely on React computing them for you. - https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state

对于没有父子关系的两个组件之间的通信,您可以设置自己的全局事件系统。在 componentDidMount() 中订阅事件,在 componentWillUnmount() 中取消订阅,并在收到事件时调用 setState()。通量模式是一种可能的安排方式。- https://facebook.github.io/react/tips/communicate-between-components.html

哪些组件应该有状态?

你的大部分组件应该简单地从 props 中获取一些数据并渲染它。但是,有时您需要响应用户输入、服务器请求或时间的流逝。为此,您使用状态。

尝试使尽可能多的组件保持无状态。通过这样做,您可以将状态隔离到最合乎逻辑的位置并最大限度地减少冗余,从而更容易推理您的应用程序。

一个常见的模式是创建几个只渲染数据的状态组件,并在层次结构中在它们上面有一个有状态的组件,通过 props 将其状态传递给它的子级。有状态组件封装了所有交互逻辑,而无状态组件以声明方式处理数据渲染。- https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-c​​omponents-should-have-state

国家应该怎么办?

状态应包含组件的事件处理程序可能会更改以触发 UI 更新的数据。在实际应用中,这些数据往往非常小且可通过 JSON 序列化。在构建有状态组件时,考虑其状态的最小可能表示,并且只将这些属性存储在 this.state 中。在 render() 内部,只需根据此状态计算您需要的任何其他信息。你会发现以这种方式思考和编写应用程序往往会导致最正确的应用程序,因为向状态添加冗余或计算值意味着你需要明确地保持它们同步,而不是依赖 React 为你计算它们。- https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-should-go-in-state

回答by mkarrfan

You can understand it best by relating it to Plain JS functions.

您可以通过将它与普通 JS 函数相关联来最好地理解它。

Simply put,

简单的说,

Stateis the local state of the component which cannot be accessed and modified outside of the component. It's equivalent to local variables in a function.

状态是组件的本地状态,不能在组件外部访问和修改。它相当于函数中的局部变量。

Plain JS Function

普通JS函数

const DummyFunction = () => {
  let name = 'Manoj';
  console.log(`Hey ${name}`)
}

React Component

反应组件

class DummyComponent extends React.Component {
  state = {
    name: 'Manoj'
  }
  render() {
    return <div>Hello {this.state.name}</div>;
  }

Props, on the other hand, make components reusable by giving components the ability to receive data from their parent component in the form of props. They are equivalent to function parameters.

另一方面,Props使组件能够以 props 的形式从其父组件接收数据,从而使组件可重用。它们等价于函数参数。

Plain JS Function

普通JS函数

const DummyFunction = (name) => {
  console.log(`Hey ${name}`)
}

// when using the function
DummyFunction('Manoj');
DummyFunction('Ajay');

React Component

反应组件

class DummyComponent extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }

}

// when using the component
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />

Credits: Manoj Singh Negi

学分:Manoj Singh Negi

Article Link: React State vs Props explained

文章链接:React State vs Props 解释

回答by broc.seib

The props vs state summary I like best is here: react-guideBig hat tip to those guys. Below is an edited version of that page:

我最喜欢的 props vs state 总结在这里:react-guide给那些家伙的大帽子提示。以下是该页面的编辑版本:



props vs state

道具 vs 状态

tl;drIf a Component needs to alter one of its attributes at some point in time, that attribute should be part of its state, otherwise it should just be a prop for that Component.

tl;dr如果组件需要在某个时间点更改其属性之一,则该属性应该是其状态的一部分,否则它应该只是该组件的道具。



props

道具

Props (short for properties) are a Component's configuration. They are received from above and immutable as far as the Component receiving them is concerned. A Component cannot change its props, but it is responsible for putting together the props of its child Components. Props do not have to just be data -- callback functions may be passed in as props.

道具(属性的简称)是组件的配置。就接收它们的组件而言,它们是从上面接收的并且是不可变的。一个 Component 不能改变它的 props,但它负责把它的子组件的 props 放在一起。道具不必只是数据——回调函数可以作为道具传入。

state

状态

The state is a data structure that starts with a default value when a Component mounts. It may be mutated across time, mostly as a result of user events.

状态是一种数据结构,在组件挂载时以默认值开始。它可能会随着时间发生变化,主要是由于用户事件。

A Component manages its own state internally. Besides setting an initial state, it has no business fiddling with the state of its children. You might conceptualize state as private to that component.

组件在内部管理自己的状态。除了设置初始状态外,它没有必要摆弄子级的状态。您可能将状态概念化为该组件的私有状态。

Changing props and state

改变道具和状态

                                                   props   state
    Can get initial value from parent Component?    Yes     Yes
    Can be changed by parent Component?             Yes     No
    Can set default values inside Component?*       Yes     Yes
    Can change inside Component?                    No      Yes
    Can set initial value for child Components?     Yes     Yes
    Can change in child Components?                 Yes     No
  • Note that both props and state initial values received from parents override default values defined inside a Component.
  • 请注意,从父项接收的 props 和 state 初始值都会覆盖组件内定义的默认值。

Should this Component have state?

这个组件应该有状态吗?

State is optional. Since state increases complexity and reduces predictability, a Component without state is preferable. Even though you clearly can't do without state in an interactive app, you should avoid having too many Stateful Components.

状态是可选的。由于状态会增加复杂性并降低可预测性,因此最好使用没有状态的组件。即使在交互式应用程序中你显然不能没有状态,但你应该避免有太多的有状态组件。

Component types

组件类型

Stateless ComponentOnly props, no state. There's not much going on besides the render() function. Their logic revolves around the props they receive. This makes them very easy to follow, and to test.

Stateless Component只有道具,没有状态。除了 render() 函数之外,没有太多事情要做。他们的逻辑围绕着他们收到的道具展开。这使它们非常易于遵循和测试。

Stateful ComponentBoth props and state. These are used when your component must retain some state. This is a good place for client-server communication (XHR, web sockets, etc.), processing data and responding to user events. These sort of logistics should be encapsulated in a moderate number of Stateful Components, while all visualization and formatting logic should move downstream into many Stateless Components.

有状态组件props 和 state。当您的组件必须保留某些状态时使用这些。这是客户端-服务器通信(XHR、Web 套接字等)、处理数据和响应用户事件的好地方。这些类型的逻辑应该封装在适量的有状态组件中,而所有可视化和格式化逻辑应该向下游移动到许多无状态组件中。

sources

来源

回答by Alireza

props(short for “properties”) and stateare both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way: props get passed to the component (similar to function parameters) whereas stateis managed within the component (similar to variables declared within a function).

props(“properties”的缩写)和state都是普通的 JavaScript 对象。虽然两者都持有影响渲染输出的信息,但它们在一个重要方面有所不同:props 传递给组件(类似于函数参数),而状态在组件内管理(类似于函数中声明的变量)。

So simply stateis limited to your current component but propscan be pass to any component you wish... You can pass the stateof the current component as propto other components...

所以简单的状态仅限于您当前的组件,但道具可以传递给您希望的任何组件......您可以将当前组件的状态作为道具传递给其他组件......

Also in React, we have stateless componentswhich only have props and not internal state...

同样在 React 中,我们有无状态组件,它们只有 props 而没有内部状态......

The example below showing how they work in your app:

下面的示例显示了它们在您的应用程序中的工作方式:

Parent(state-full component):

父级(全状态组件):

class SuperClock extends React.Component {

  constructor(props) {
    super(props);
    this.state = {name: "Alireza", date: new Date().toLocaleTimeString()};
  }

  render() {
    return (
      <div>
        <Clock name={this.state.name} date={this.state.date} />
      </div>
    );
  }
}

Child(state-less component):

(无状态组件):

const Clock = ({name}, {date}) => (
    <div>
      <h1>{`Hi ${name}`}.</h1>
      <h2>{`It is ${date}`}.</h2>
    </div>
);

回答by Aftab22

The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component.

props 和 state 之间的主要区别在于 state 是内部的并且由组件本身控制,而 props 是外部的并且由渲染组件的任何东西控制。

function A(props) {
  return <h1>{props.message}</h1>
}

render(<A message=”hello” />,document.getElementById(“root”));



class A extends React.Component{  
  constructor(props) {  
    super(props)  
    this.state={data:"Sample Data"}  
  }  
  render() {
    return(<h2>Class State data: {this.state.data}</h2>)  
  } 
}

render(<A />, document.getElementById("root"));

State VS Props

状态 VS 道具

  • State can be changed (Mutable)
  • Whereas Props can't (Immutable)
  • 状态可以改变(可变)
  • 而道具不能(不可变)

回答by Nesha Zoric

Basically, the difference is that stateis something like attributes in OOP: it's something localto a class (component), used to better describe it. Propsare like parameters- they are passedto a component from the caller of a component (the parent) : as if you called a function with certain parameters.

基本上,不同之处在于状态类似于 OOP 中的属性:它是类(组件)的局部内容,用于更好地描述它。props就像参数——它们从组件的调用者(父组件)传递给组件:就好像你用某些参数调用了一个函数。

回答by Vivek Mehta

Both stateand propsin react are used to control data into a component, generally props are set by parent and passed to child components and they are fixed throughout the component. For data that is going to change,we have to use state. And props are immutablewhile states are mutable, if you want to change props you can do from parent component and then pass it to child components.

React 中的stateprops都用于控制数据到组件中,通常 props 由父组件设置并传递给子组件,并且它们在整个组件中都是固定的。对于将要更改的数据,我们必须使用状态。props 是不可变的,而 state 是可变的,如果你想改变 props,你可以从父组件做,然后将它传递给子组件。

回答by Poulima Biswas

Props : Props is nothing but property of component and react component is nothing but a javascript function.

Props :Props 只是组件的属性,而 react 组件只是一个 javascript 函数。

  class Welcome extends React.Component {
    render() {
      return <h1>Hello {this.props.name}</h1>;
    }
  }

const element = ;

常量元素 = ;

here <Welcome name="Sara" />passing a object {name : 'Sara'} as props of Welcome component. To pass data from one parent component to child component we use props. Props is immutable. During a component's life cycle props should not change (consider them immutable).

这里<Welcome name="Sara" />传递一个对象 {name : 'Sara'} 作为 Welcome 组件的道具。为了将数据从一个父组件传递到子组件,我们使用 props。道具是不可变的。在组件的生命周期中,道具不应该改变(认为它们是不可变的)。

State: state is accessible only within Component. To keep track of data within component we use state. we can change state by setState. If we need to pass state to child we have to pass it as props.

状态:状态只能在组件内访问。为了跟踪组件内的数据,我们使用状态。我们可以通过 setState 改变状态。如果我们需要将 state 传递给 child 我们必须将它作为 props 传递。

class Button extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
  }

  updateCount() {
    this.setState((prevState, props) => {
      return { count: prevState.count + 1 }
    });
  }

  render() {
    return (<button
              onClick={() => this.updateCount()}
            >
              Clicked {this.state.count} times
            </button>);
  }
}

回答by Akanksha gore

State:

状态:

  1. states are mutable.
  2. states are associated with the individual components can't be used by other components.
  3. states are initialize on component mount.
  4. states are used for rendering dynamic changes within component.
  1. 状态是可变的。
  2. 状态与单个组件相关联,不能被其他组件使用。
  3. 状态在组件安装时初始化。
  4. 状态用于呈现组件内的动态变化。

props:

道具:

  1. props are immutable.
  2. you can pass props between components.
  3. props are mostly used to communicate between components.You can pass from parent to child directly. For passing from child to parent you need use concept of lifting up states.
  1. props 是不可变的。
  2. 您可以在组件之间传递道具。
  3. props 主要用于组件之间的通信。可以直接从父级传递给子级。为了从孩子传递给父母,您需要使用提升状态的概念。

class Parent extends React.Component{
  render()
  {
     return(
        <div>
            <Child name = {"ron"}/>
        </div>
      );
  }
}

class Child extends React.Component{
{
    render(){
      return(
         <div>
              {this.props.name}
        </div>
      );
     }
}