我在看Pluralsight关于React的课程,老师说道具不应该被改变。我现在正在读一篇关于道具vs.国家的文章(uberVU/react-guide),它说

道具和状态更改都会触发呈现更新。

文章后面说:

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

所以道具可以改变,但它们应该是不可变的? 什么时候应该使用道具,什么时候应该使用状态? 如果你有一个React组件需要的数据,它应该通过道具或设置在React组件通过getInitialState?


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

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

父类的childsName的状态值变成子类的this.props.name。从子进程的角度来看,名称道具是不可变的。如果它需要改变,父进程只需要改变它的内部状态:

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

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

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

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

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

亲子交流,只需传递道具即可。

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

使用道具将数据和事件处理程序传递给你的子组件。

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

道具

是不可变的 它可以让React进行快速参考检查 用于从视图控制器向下传递数据 顶级组件 有更好的表现 使用它将数据传递给子组件

状态

是否应该在视图控制器中进行管理 顶级组件 是可变的 表现更差 不应该从子组件访问 用道具把它传下去

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 stateless components 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


Basically, props and state are two ways the component can know what and how to render. Which part of the application state belongs to state and which to some top-level store, is more related to your app design, than to how React works. The simplest way to decide, IMO, is to think, whether this particular piece of data is useful for application as a whole, or it's some local information. Also, it's important to not duplicate state, so if some piece of data can be calculated from props - it should calculated from props.

For example, let's say you have some dropdown control (which wraps standart HTML select for custom styling), which can a) select some value from list, and b) be opened or closed (i.e., the options list displayed or hidden). Now, let's say your app displays a list of items of some sort and your dropdown controls filter for list entries. Then, it would be best to pass active filter value as a prop, and keep opened/closed state local. Also, to make it functional, you would pass an onChange handler from parent component, which would be called inside dropdown element and send updated information (new selected filter) to the store immediately. On the other hand, opened/closed state can be kept inside dropdown component, because the rest of the application doesn't really care if the control is opened, until user actually changes it value.

下面的代码是不完全工作,它需要css和处理下拉单击/模糊/改变事件,但我想保持示例最小。希望这有助于理解其中的区别。

const _store = {
    items: [
    { id: 1, label: 'One' },
    { id: 2, label: 'Two' },
    { id: 3, label: 'Three', new: true },
    { id: 4, label: 'Four', new: true },
    { id: 5, label: 'Five', important: true },
    { id: 6, label: 'Six' },
    { id: 7, label: 'Seven', important: true },
    ],
  activeFilter: 'important',
  possibleFilters: [
    { key: 'all', label: 'All' },
    { key: 'new', label: 'New' },
    { key: 'important', label: 'Important' }
  ]
}

function getFilteredItems(items, filter) {
    switch (filter) {
    case 'all':
        return items;

    case 'new':
        return items.filter(function(item) { return Boolean(item.new); });

    case 'important':
        return items.filter(function(item) { return Boolean(item.important); });

    default:
        return items;
  }
}

const App = React.createClass({
  render: function() {
    return (
            <div>
            My list:

            <ItemList   items={this.props.listItems} />
          <div>
            <Dropdown 
              onFilterChange={function(e) {
                _store.activeFilter = e.currentTarget.value;
                console.log(_store); // in real life, some action would be dispatched here
              }}
              filterOptions={this.props.filterOptions}
              value={this.props.activeFilter}
              />
          </div>
        </div>
      );
  }
});

const ItemList = React.createClass({
  render: function() {
    return (
      <div>
        {this.props.items.map(function(item) {
          return <div key={item.id}>{item.id}: {item.label}</div>;
        })}
      </div>
    );
  }
});

const Dropdown = React.createClass({
    getInitialState: function() {
    return {
        isOpen: false
    };
  },

  render: function() {
    return (
        <div>
            <select 
            className="hidden-select" 
          onChange={this.props.onFilterChange}
          value={this.props.value}>
            {this.props.filterOptions.map(function(option) {
            return <option value={option.key} key={option.key}>{option.label}</option>
          })}
        </select>

        <div className={'custom-select' + (this.state.isOpen ? ' open' : '')} onClick={this.onClick}>
            <div className="selected-value">{this.props.activeFilter}</div>
          {this.props.filterOptions.map(function(option) {
            return <div data-value={option.key} key={option.key}>{option.label}</div>
          })}
        </div>
      </div>
    );
  },

  onClick: function(e) {
    this.setState({
        isOpen: !this.state.isOpen
    });
  }
});

ReactDOM.render(
  <App 
    listItems={getFilteredItems(_store.items, _store.activeFilter)} 
    filterOptions={_store.possibleFilters}
    activeFilter={_store.activeFilter}
    />,
  document.getElementById('root')
);

我最喜欢的道具vs状态总结在这里:反应指南向这些家伙致敬。以下是该页面的编辑版本:


道具vs状态

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


道具

道具(属性的简称)是组件的配置。它们是从上面接收的,对于接收它们的组件来说是不可变的。组件不能更改它的道具,但它负责将其子组件的道具组合在一起。道具不一定只是数据——回调函数可以作为道具传递进来。

状态

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

组件在内部管理自己的状态。除了设置一个初始状态外,它没有权利修改它的子进程的状态。您可以将状态概念化为该组件的私有状态。

改变道具和状态

                                                   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

注意,从父组件接收到的props和state初始值都会覆盖组件内部定义的默认值。

这个组件应该有状态吗?

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

组件类型

无状态组件只有道具,没有状态。除了render()函数之外,没有什么事情要做。他们的逻辑围绕着他们得到的道具展开。这使得它们非常容易遵循和测试。

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

来源

关于“props”和“state”的问题-谷歌组 React中的思考:确定你的状态应该在哪里


在回答最初关于道具不可变的问题时,我们说它们在子组件中是不可变的,但在父组件中是可以改变的。


状态是react处理组件所持有信息的方式。

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

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

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

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

那么,与我们在面向对象编程中总是使用对象属性有什么不同呢?通常,在您的状态中保存的信息并不是静态的,它会随着时间的推移而变化,您的视图需要更新以反映这些变化。State以一种简单的方式提供了此功能。

状态是不可改变的!我再怎么强调也不为过。这意味着什么?这意味着你永远不应该做这样的事情。

 state.key2 = newValue;

正确的做法是:

this.setState({ key2: newValue });

使用这个。setState你的组件在更新周期中运行,如果状态的任何部分发生变化,你的组件呈现方法将被再次调用以反映这些变化。

请查看react文档以获得更详细的解释: https://facebook.github.io/react/docs/state-and-lifecycle.html


一般来说,一个组件(父组件)的状态是子组件的prop。

State resides within a component where as props are passed from parent to child. Props are generally immutable. 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} ) } }

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


state -这是一个特殊的可变属性,保存组件数据。它在Componet挂载时具有默认值。

props -这是一个特殊的属性,本质上是不可变的,用于从父到子的值传递。props只是组件之间的通信通道,总是从顶部(父组件)移动到底部(子组件)。

下面是结合状态和道具的完整示例

<!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
        <title>state&props example</title>

        <script src="https://unpkg.com/react@0.14.8/dist/react.min.js"></script>
        <script src="https://unpkg.com/react-dom@0.14.8/dist/react-dom.min.js"></script>
        <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>

      </head>
      <body>
      <div id="root"></div>
        <script type="text/babel">

            var TodoList = React.createClass({
                render(){
                    return <div className='tacos-list'>
                                {
                                    this.props.list.map( ( todo, index ) => {
                                    return <p key={ `taco-${ index }` }>{ todo }</p>;
                            })}
                            </div>;
                }
            });

            var Todo = React.createClass({
                getInitialState(){
                    return {
                        list : [ 'Banana', 'Apple', 'Beans' ]       
                    }
                },
                handleReverse(){
                    this.setState({list : this.state.list.reverse()});
                },
                render(){
                    return <div className='parent-component'>
                              <h3 onClick={this.handleReverse}>List of todo:</h3>
                              <TodoList list={ this.state.list }  />
                           </div>;
                }
            });

            ReactDOM.render(
                <Todo/>,
                document.getElementById('root')
            );

        </script>
      </body>
      </html>

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


React组件使用state来读取/写入内部变量,这些变量可以通过以下方式更改/突变:

this.setState({name: 'Lila'})

React props是一个特殊的对象,允许程序员从父组件中获取变量和方法到子组件中。

它有点像房子的门窗。道具也是不可变的子组件不能改变/更新他们。

当父组件更改道具时,有几个方法可以帮助监听。


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

State就像组件中的局部变量。你可以操纵 使用set state获取state的值。然后可以传递state的值 例如,您的子组件。 Props是位于redux存储中的值 来源于来源于减速器的状态。您的组件 应该连接到redux从道具中获取值。你也可以通过 你的props值给你的子组件


道具只是属性的简写。道具是组件之间相互交流的方式。如果你熟悉React,那么你应该知道道具是从父组件向下流动的。

还有一种情况是,你可以有默认的道具,这样即使父组件没有传递道具,道具也会被设置。

这就是为什么人们认为React具有单向数据流。这需要一些理解,我可能会在后面的博客中对此进行讨论,但现在只要记住:数据从父流向子。道具是不可变的(是指不变的)

所以我们很高兴。组件从父组件接收数据。都整理好了,对吧?

嗯,不完全是。当组件从父组件以外的对象接收数据时会发生什么?如果用户直接向组件输入数据呢?

这就是我们有状态的原因。

状态

道具不应该改变,所以状态上升。组件通常没有状态,因此被称为无状态。使用状态的组件称为有状态的。在聚会上随便说说你的小秘密,然后看着人们慢慢地离你而去。

所以使用状态是为了让组件可以在它所做的任何渲染之间跟踪信息。当你setState时,它更新状态对象,然后重新渲染组件。这非常酷,因为这意味着React会处理困难的工作,并且速度非常快。

作为状态的一个小例子,这里是一个搜索栏的片段(如果你想了解更多关于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);
 }
}

总结

道具和状态的作用类似,但使用方式不同。大多数组件可能是无状态的。

道具用于将数据从父组件传递给子组件或由组件本身传递。它们是不可变的,因此不会被改变。

State用于可变数据或将更改的数据。这对于用户输入特别有用。以搜索栏为例。用户将输入数据,这将更新他们所看到的内容。


基本上,区别在于状态类似于OOP中的属性:它是类(组件)的局部属性,用于更好地描述它。道具就像参数一样——它们从组件的调用者(父组件)传递给组件:就像你调用一个带有特定参数的函数一样。


props (properties的缩写)和state都是简单的JavaScript 对象。而两者都持有影响输出的信息 渲染,他们在一个重要的方面是不同的:道具被传递到 组件(类似于函数参数),而状态为 在组件中管理(类似于在组件中声明的变量 功能)。

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

同样在React中,我们有无状态的组件,它们只有道具,没有内部状态……

下面的例子展示了它们如何在你的应用程序中工作:

父组件(全状态组件):

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

你可以通过将它与Plain联系起来来更好地理解它 JS函数。

简单地说,

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

普通JS函数

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

反应组件

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

另一方面,通过赋予组件以道具形式从父组件接收数据的能力,道具可以使组件可重用。它们等价于函数参数。

普通JS函数

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

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

反应组件

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

}

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

工作人员:Manoj Singh Negi

文章链接:解释了反应状态与道具


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

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

Const元素=;

这里<Welcome name="Sara" />传递一个对象{name: 'Sara'}作为Welcome组件的道具。为了将数据从一个父组件传递给子组件,我们使用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>);
  }
}

状态:

状态是可变的。 状态与单个组件相关联,不能被其他组件使用。 在组件挂载时初始化状态。 状态用于呈现组件内的动态更改。

道具:

道具是不可变的。 您可以在组件之间传递道具。 道具主要用于组件之间的通信。你可以直接从父母传递给孩子。用于从孩子传递给父母 你需要使用提升状态的概念。

类Parent扩展React。组件{ 呈现() { 回报( < div > <孩子的名字= {"ron"}/> . < / div > ); } } 子类扩展React。组件{ { 呈现(){ 回报( < div > {this.props.name} < / div > ); } }


简而言之。

道具值不能改变[不可变] 使用setState方法[mutable]可以改变状态值


用户在应用程序的某个地方输入了一些数据。

在其中输入数据的组件应该在其状态中拥有该数据,因为它需要在数据输入期间操作和更改它 在应用程序的其他任何地方,数据都应该作为道具传递给所有其他组件

所以,是的,道具是在变化的,但它们是从“源头”改变的,然后简单地从那里向下流动。所以道具在接收它们的组件的上下文中是不可变的。

例如,在一个参考数据屏幕上,用户编辑一个供应商列表将在状态下管理它,然后会有一个操作,导致更新的数据保存在ReferenceDataState中,它可能比AppState低一级,然后这个供应商列表将作为道具传递给所有需要使用它的组件。


道具是在渲染时传递给组件的值、对象或数组。这些道具通常是组件中创建UI、设置某些默认功能或填充字段所需的值。道具也可以以父组件传递给子组件的函数的形式出现。

状态在组件(子组件或父组件)中进行管理。

下面是我找到的一个支持这一点的定义:


简单的解释是: STATE是组件的局部状态,例如color = "blue"或animation=true等。用这个。setState更改组件的状态。 PROPS是组件如何相互通信(将数据从父组件发送给子组件)以及如何使组件可重用。


State是你的数据,是可变的,你可以对它做任何你需要的事情,props是只读数据,通常当你传递props时,你已经使用了你的数据,你需要子组件来渲染它,或者如果你的props是一个函数,你调用它来执行任务


状态是真相的起源,是您的数据存在的地方。 你可以说这种状态是通过道具表现出来的。

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

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

所以这些道具就像是将数据从原点传递到功能组件的管道。


在React中,状态存储数据和道具。它与后者的不同之处在于存储的数据可以通过不同的更改进行修改。它们只不过是用JavaScript编写的对象,所以它们可以包含数据或代码,表示您想要建模的信息。如果您需要更多的细节,建议您阅读这些出版物 在React和 React中道具的使用


Props:表示“只读”数据,是不可变的,引用父组件的属性。

状态:表示可变数据,它最终会影响页面上呈现的内容,并由组件本身内部管理,通常会由于用户输入而不断更改。


主要的区别是状态是组件私有的,只能在组件内部更改,而道具只是静态值和键的子组件,通过父组件传递,不能在子组件内部更改


道具——你不能改变它的值。 States—您可以在代码中更改它的值,但当呈现发生时它将是活动的。


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

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

状态可以改变(可变的) 而道具不能(不可变)


react中“state”和“props”的区别。

React根据状态控制和渲染DOM。有两种类型的组件状态:props是组件之间传输的状态,state是组件的内部状态。Props用于将数据从父组件传输到子组件。组件在内部也有自己的状态:只能在组件内部修改的状态。

一般来说,某个组件的状态可以是子组件的道具,道具会传递给子组件,这是在父组件的呈现方法中声明的


React组件使用state来读取/写入内部变量,这些变量可以通过以下方式更改/突变:

this.setState({name: 'Lila'})

React props是一个特殊的对象,允许程序员从父组件中获取变量和方法到子组件中。

它有点像房子的门窗。道具也是不可变的子组件不能改变/更新他们。

当父组件更改道具时,有几个方法可以帮助监听。


状态驻留在组件中,作为道具从父组件传递给子组件。 道具通常是不可变的。

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

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


摘自:Andrea Chiarelli的书《开始React:用React简化前端开发工作流,增强应用程序的用户体验》:

Every React component has a props property. The purpose of this property is to collect data input passed to the component itself. JSX attribute is attached to a React element, a property with the same name is attached to the props object. So, we can access the passed data by using the attached property. In addition, the immutability of props allows us to think of components as pure functions, which are functions that have no side effects (since they don't change their input data). We can think of data passing from one component to another as a unidirectional data flow, from the parent component toward the child components. This gives us a more controllable system.

React provides a mechanism to support the automatic rendering of a component when data changes. Such a mechanism is based on the concept of state. React state is a property that represents data that changes over time. Every component supports the state property, but it should be used carefully. Components that store data that can change over time are said to be stateful components. A stateful component stores the state in the this.state property. To inform a component that the state has changed, you must use the setState() method. State initialization is the only case where you can assign a value to the this.state property without using setState().

setState()将新数据与已包含在状态中的旧数据合并,并覆盖先前的状态 setState()会触发render()方法的执行,所以永远不要显式地调用render()


这是我在使用react时学到的。

组件使用Props从外部环境中获取数据,例如另一个组件(纯组件、函数组件或类)或一般类或javascript/typescript代码 用于管理组件内部环境的状态意味着组件内部的数据变化


道具

用于在子组件中传递数据的道具 道具在组件(子组件)外部更改值

状态

在类组件中使用状态 状态更改组件内的值 如果呈现页面,则调用setState来更新DOM(更新页面) 值)

状态在反应中起着重要的作用


主要的区别是状态只能在组件内部处理,而道具则在组件外部处理。如果我们从外部获取数据并进行处理,在这种情况下,我们应该使用状态。


道具和状态在某种程度上是相同的,它们都会触发重渲染。不同之处在于,道具来自于父组件,状态在当前组件中管理。状态是可变的,道具是不可变的


props是JavaScript对象,传递给组件,保存配置属性。 props是接收组件不可更改的 state是在Component中管理的JavaScript对象,保存它的内部状态。 更新可以触发重新渲染


简单地说:

状态由组件自己管理。它是可重用的、组件私有的、可修改的。 道具从父母传递给孩子。它是一个单向流,子组件是只读的。父组件的状态可以作为道具传递给子组件。


大多数时候,你的子组件是无状态的,这意味着它们代表了它的父组件给它的数据/信息。

另一方面,状态处理的是处理组件本身,状态可以在组件内部通过setState和useState钩子改变。

例如

class Parent extends Component{
  constructor(props){
    super(props);
    this.state = {
      fruit: 'apple'
    }
    this.handleChange = this.handleChange.bind(this)
  }

  handleChange(){
    this.setState({fruit: 'mango'})
  }
  render(){
    return (
      <div>
      <Child  fruit={this.state.fruit} />
      <button onClick={this.handleChange}>Change state</button>
      </div>
    )
  }
}

当点击按钮时,父类将其状态从apple更改为mango,并将其状态作为道具传递给子组件。现在,没有状态的子组件根据父组件的状态显示不同的标题。

class Child extends Component{

  render(){
    return(
      <h1>I have received a prop {this.props.fruit}</h1>
    )
  }
}

所以在根级别上,道具是父进程与子进程的通信,而状态是描述父进程的情况等。


State:具有内部值,这意味着只在该类组件中有效,因此不能将其传递给另一个组件。

道具:另一方面,你可以将道具从父对象传递给子对象或从子对象传递给父对象。


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


给出最简单的解释,补充上述评论:

根据React的官方文档,他们将“状态”视为

To “remember” things, components use state.

props可以理解为从父组件传递给子组件的变量。

如果你想在应用中记住一些东西,你会使用状态如果你想传递数据,你会使用道具。

让我给你另一个类比,假设你想把你脑子里的前25个自然数的序列相加。

1+2+3+4.....

从1开始,然后加2,现在是3,然后加到现在的总数(6),然后加4到现在的总数(6),所以新的总数是10。

当前的总和是程序的状态,假设您需要找到总和的平均值。你要把这个和代入一个方程,然后把这个和作为道具传下去。

希望这能说得通。


React props和state之间的主要区别是props是不可变的,一旦组件接收到一个props,它就不能改变它的值,而在另一方面,React state是可变的,组件可以根据需要的时间自由改变它的值。


State是react中的一个特殊变量,用于在组件更新时重新渲染组件

状态对于组件本身是私有的。也就是说,它不能在组件外部被访问或修改。setState/用于更新状态的钩子。每当状态更新时,组件重新呈现

状态是可变的

道具是组件的输入,并使用道具数据呈现内容

道具是不可变的(Object。冻结= true)


我们可以改变states的值但我们不能改变props的值,或者我们可以说props是不可变的而states是可变的


“Props”是传递给组件(1)的外部输入,“state”是由组件(2)管理的内部私有数据。


在react中,我们通常使用模块来分离组件。有时分离的组件需要在它们内部共享数据。如果父组件有一些数据应该在子组件上共享,那么道具是解决方案。我们可以使用从父母到孩子的道具共享数据。Props是不可变的,这意味着您不能更改数据。

另一方面,状态用于跟踪数据中的任何变化。您可以将状态视为数据的存储和可以更新该数据的函数。状态是可变的。您可以在同一组件中使用setState函数更改状态


在React中,道具和状态之间有一些关键的区别。道具是不可变的——一旦设置好,就不能更改。另一方面,状态可以在任何时候改变。道具也从父组件传递给子组件,而状态是单个组件的局部状态。


我想用一种简单的方式向你解释状态和道具:

状态

我们使用状态来存储一些数据。它也像一个变量,当你改变它时,你的组件将再次呈现。

要使用状态,你需要导入useState钩子:

import { useState } from 'react';
const [state_name,function_name] = useState(initial_value);

您可以通过state_name访问您的状态,也可以通过function_name更改它并为其设置一个新值。

更多信息:https://reactjs.org/docs/state-and-lifecycle.html

道具

它是一种将数据从一个组件发送到另一个组件的机制。它看起来也像CSS中的属性。例如:

<Component props_value={custom_function} />

你可以发送一个自定义函数到组件,并接收它进行操作。

更多信息:https://reactjs.org/docs/components-and-props.html