React中state和props有什么区别?

JavaScript

Harry十三

2020-03-09

我正在观看有关React的Pluralsight课程,并且讲师指出,不应更改道具。我现在正在阅读有关道具与状态的文章(uberVU / react-guide),它说

道具和状态更改都会触发渲染更新。

文章稍后会说:

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

  • 所以道具可以改变,但它们应该是不变的?
  • 什么时候应该使用道具,什么时候应该使用状态?
  • 如果您有React组件需要的数据,是否应该通过prop或在React组件中通过setup进行设置getInitialState

第348篇《React中state和props有什么区别?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

20个回答
Jim前端Near 2020.03.09

状态位于组件从父级传递到子级的组件内。道具通常是不可变的。

class Parent extends React.Component {
    constructor() {
        super();
        this.state = {
            name : "John",
        }
    }
    render() {
        return (
            <Child name={this.state.name}>
        )
    }
}

class Child extends React.Component {
    constructor() {
        super();
    }

    render() {
        return(
            {this.props.name} 
        )
    }
}

在上面的代码中,我们有一个父类(父类),其父类的状态作为名称传递给子组件(子类)作为道具,子组件使用{this.props.name}进行渲染。

老丝Near 2020.03.09

道具:表示“只读”数据,该数据是不可变的,是指来自父级组件的属性。

状态:表示可变数据,最终会影响页面上呈现的内容以及由组件本身在内部进行管理的内容,并且通常由于用户输入而导致超时变化。

村村Mandy 2020.03.09

状态是真理的起源,您的数据生活在这里。 您可以说国家通过道具表现出来。

为组件提供道具可以使您的UI与数据保持同步。组件实际上只是一个返回标记的函数。

给定相同的道具(用于显示的数据),它将始终产生相同的标记

因此,道具就像将数据从源头传送到功能组件的管道一样。

Davaid阳光 2020.03.09

简单的解释是:STATE是组件的局部状态,例如color =“ blue”或animation = true等。使用this.setState更改组件的状态。PROPS是组件之间相互通信(将数据从父级发送到子级)并使组件可重用的方式。

StafanTony 2020.03.09

状态是您的数据,是可变的,您可以使用它做任何您需要的事情,道具是只读数据,通常当您传递道具时,您已经使用了数据,并且需要子组件来呈现它,或者您的道具是一个道具。你调用它执行任务的功能

TonyStafan 2020.03.09

这是我目前关于状态与道具之间的解释的观点

  1. 状态就像组件内部的局部变量。您可以使用set state来操纵state的值。然后,您可以例如将state的值传递给子组件。

  2. 道具是完全位于您的redux存储内的值,它实际上来自于reducer产生的状态。您的组件应连接到redux以从props获取值。您还可以将props值传递给子组件

Pro神无樱 2020.03.09

在回答有关道具是不可变的最初问题时,就子组件而言,据说道具是不可变的,但在父组件中却是可变的。

W先生 2020.03.09

反应中“状态”和“道具”之间存在一些差异。

React根据状态控制和呈现DOM。组件状态有两种类型:props是在组件之间转移的状态,而state是组件的内部状态。道具用于从父组件到子组件的数据传输。组件内部也有自己的状态:状态只能在组件内部进行修改。

通常,某些组件的状态可能是子组件的道具,道具将传递给子组件,这在父组件的渲染方法中声明

蛋蛋Near 2020.03.09
  • 道具 ---你不能改变它的价值。
  • 状态 ---您可以在代码中更改其值,但是在进行渲染时它将处于活动状态。
Harry伽罗 2020.03.09

在React中,状态存储数据以及道具。与后者的区别在于,可以通过不同的更改来修改存储的数据。这些不过是用平面JavaScript编写的对象,因此它们可以包含数据或代码,代表您要建模的信息。如果您需要更多的细节,建议你看这些出版物 中使用做出反应的国家道具的用途作出反应

小宇宙猴子 2020.03.09

通常,一个组件(父组件)的状态是子组件的道具。

  1. 状态位于组件从父级传递到子级的组件内。
  2. 道具通常是不可变的。

    class Parent extends React.Component {
        constructor() {
            super();
            this.state = {
                name : "John",
            }
        }
        render() {
            return (
                <Child name={this.state.name}>
            )
        }
    }
    
    class Child extends React.Component {
        constructor() {
            super();
        }
    
        render() {
            return(
                {this.props.name} 
            )
        }
    }
    

在上面的代码中,我们有一个父类(父类),其父类的状态作为名称传递给子组件(子类)作为道具,子组件使用{this.props.name}进行渲染。

乐米亚 2020.03.09

您有一些用户正在应用程序中输入的数据。

  1. 输入数据的组件应具有此数据的状态,因为它需要在数据输入期间进行操作和更改

  2. 在应用程序的其他任何地方,数据都应作为道具传递给所有其他组件

所以是的,道具正在发生变化,但是它们在“源”处发生了变化,然后将仅从那里流下来。因此,道具在组件接收它们的上下文中是不可变

例如,参考数据屏幕,用户在其中编辑供应商列表将在状态下进行管理,然后执行一个操作,使更新的数据保存在ReferenceDataState中,该数据可能位于AppState的下一级,然后此供应商列表将作为道具传递到需要使用它的所有组件。

A十三 2020.03.09

简而言之。

道具值无法更改[不可变]

状态值可以使用setState方法[mutable]进行更改

小哥梅 2020.03.09

州:

  1. 状态是可变的。
  2. 状态与各个组件相关联,其他组件无法使用。
  3. 状态在组件安装时初始化。
  4. 状态用于呈现组件内的动态更改。

道具:

  1. 道具是一成不变的。
  2. 您可以在组件之间传递道具。
  3. 道具通常用于组件之间的通信。您可以直接从父级传递到子级。为了从孩子传给父母,您需要使用提升状态的概念。

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

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

猴子十三 2020.03.09

Props simply are shorthand for properties. Props are how components talk to each other. If you’re at all familiar with React then you should know that props flow downwards from the parent component.

There is also the case that you can have default props so that props are set even if a parent component doesn’t pass props down.

This is why people refer to React as having uni-directional data flow. This takes a bit of getting your head around and I’ll probably blog on this later, but for now just remember: data flows from parent to child. Props are immutable (fancy word for it not changing)

So we’re happy. Components receive data from the parent. All sorted, right?

Well, not quite. What happens when a component receives data from someone other than the parent? What if the user inputs data directly to the component?

Well, this is why we have state.

STATE

Props shouldn’t change, so state steps up. Normally components don’t have state and so are referred to as stateless. A component using state is known as stateful. Feel free to drop that little tidbit at parties and watch people edge away from you.

So state is used so that a component can keep track of information in between any renders that it does. When you setState it updates the state object and then re-renders the component. This is super cool because that means React takes care of the hard work and is blazingly fast.

As a little example of state, here is a snippet from a search bar (worth checking out this course if you want to learn more about React)

Class SearchBar extends Component {
 constructor(props) {
  super(props);
this.state = { term: '' };
 }
render() {
  return (
   <div className="search-bar">
   <input 
   value={this.state.term}
   onChange={event => this.onInputChange(event.target.value)} />
   </div>
   );
 }
onInputChange(term) {
  this.setState({term});
  this.props.onSearchTermChange(term);
 }
}

SUMMARY

Props and State do similar things but are used in different ways. The majority of your components will probably be stateless.

Props are used to pass data from parent to child or by the component itself. They are immutable and thus will not be changed.

State is used for mutable data, or data that will change. This is particularly useful for user input. Think search bars for example. The user will type in data and this will update what they see.

宝儿小胖 2020.03.09

状态是响应处理组件所拥有信息的方式。

假设您有一个需要从服务器获取一些数据的组件。您通常希望通知用户请求是否正在处理,请求是否失败等。这是一条信息,与该特定组件有关。这是国家进入游戏的地方。

通常,定义状态的最佳方法如下:

class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = { key1: value1, key2: value2 }    
  }
}

但是在最新版本的react native中,您可以执行以下操作:

class MyComponent extends React.Component {
  state = { key1: value1, key2: value2 }    
}

这两个示例以完全相同的方式执行,只是语法上的改进。

那么,有什么不同于我们在OO编程中仅使用对象属性的区别?通常,您所处状态中的信息并不是静态的,它会随着时间而变化,您的视图将需要更新以反映此变化。State以简单的方式提供此功能。

状态是无法改变的!我对此没有施加足够的压力。这是什么意思?这意味着您永远不要做这样的事情。

 state.key2 = newValue;

正确的做法是:

this.setState({ key2: newValue });

使用this.setState,您的组件将在更新周期中运行,并且如果状态的任何部分发生更改,则将再次调用Component渲染方法以反映此更改。

检查react docs以获取更多扩展说明:https : //facebook.github.io/react/docs/state-and-lifecycle.html

Davaid小宇宙 2020.03.09

两个状态道具中发生反应被用来控制数据到一个组件,一般道具由父设置并传递到子组件和它们固定整个组件。对于将要更改的数据,我们必须使用状态。而且道具是不可变的,而状态是可变的,如果要更改道具,可以从父组件执行,然后将其传递给子组件。

Stafan路易 2020.03.09

基本上,区别在于状态类似于OOP中的属性状态类(组件)的局部内容,用于更好地描述状态。道具就像参数一样 -它们是从组件的调用者(父对象)传递给组件的:就像您使用某些参数调用函数一样。

L猴子 2020.03.09

道具和状态之间的主要区别在于,状态是内部的,并且由组件本身控制,而道具是外部的,并且由呈现组件的任何东西控制。

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

状态VS道具

  • 状态可以更改(可变)
  • 而道具不能(不变)
LEYJim 2020.03.09

props (short for “properties”) and state are 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 state is managed within the component (similar to variables declared within a function).

So simply state is limited to your current component but props can be pass to any component you wish... You can pass the state of the current component as prop to other components...

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

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

父级(全状态组件):

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

子级(无状态组件):

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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android