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

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

文章后面说:

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

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


当前回答

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

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

其他回答

一般来说,一个组件(父组件)的状态是子组件的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}渲染它。

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

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

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

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

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

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

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

你可以通过将它与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

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