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

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

文章后面说:

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

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


当前回答

道具

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

状态

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

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

其他回答

道具和状态是相关的。一个组件的状态通常会成为子组件的道具。道具在父元素的呈现方法中作为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中的一个特殊变量,用于在组件更新时重新渲染组件

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

状态是可变的

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

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

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

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

摘自: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()