道具和状态在 REACTjs 中如何工作?

How does props and state work in REACTjs?

我是 reactjs 的新手。我不太明白 propsstate 是如何工作的。根据我的研究,我发现道具从 parent 传递到 child。并且状态只能在单个组件中使用。但是当我看到下面的这些代码时,我不知道它是如何工作的。有人可以为我提供一个很好的例子和解释。谢谢

不仅如此 letvar

有什么区别
default class WildList extends React.Component {

    constructor(props){
    super(props);
    this.props = props;

    let {keyword, dealstatus} = this.props;

    this.state = {
    keyword
    }
    }

    }

PS = 这个 WildList class 也在不同的组件中使用。

状态 - 这是在组件内部维护的数据。它是本地的或由该特定组件拥有。组件本身将使用 setState 函数更新状态。

Props - 从父组件传入的数据。 props 在接收它们的子组件中是只读的。但是也可以传递回调函数,在child内部执行,发起更新。

区别在于哪个组件拥有数据。状态在本地拥有并由组件本身更新。道具由父组件拥有并且是只读的。仅当将回调函数传递给子级以触发上游更改时,道具才能更新。

State 和 Props 解释

还有let和var的解释here

而且你应该使用搜索功能,并且始终只问一个问题。

React 中,State 包含有关使用它的组件的发生或值的信息。我们可以从state中读取值,也可以在state中设置值。

另一方面,Props 是只读的。哪些是从父组件传递来与子组件共享父组件的 state。您可以像这样修改场景:

default class WildList extends React.Component {
    constructor(props){
      super(props);
      this.state = {
        keyword: this.props.keyword
      }
    }
 }

希望对您有所帮助。

简单状态特定于单个组件。您可以在状态中定义属性。通过 setstate 更改状态后,页面将再次呈现。道具示例如下。

export default class Devices extends Component {
 constructor(props) {
    super(props);
    this.state = {
      userName: "Name 1",
      itemCount: 0, // this property can use within the Devices Component not in Device detail
     }
  }

  render() {
     .....
     //you can pass username to DeviceDetail page 
     <div>
          <DeviceDetail userName={this.state.userName} />
     </div>
}
}

//Inside DeviceDetail class
export default class DeviceDetail extends Component {

    constructor(props) {
        super(props);
        this.state = {
            userName: props.userName, //you can call username using props
        }
    }
}


Var 与 let

  getAllDevices = () => {
    var totalDevicesCount = 0; //  property is initially in the global scope. 

    let apiUrl = ....URL
    var response = fetch(apiUrl);
    const data = response.json();
    totalDevicesCount = data.length;

    if (data.length > 0) {
      this.state.itemCount = totalDevicesCount; // Since this is Var can use inside different block as well but inside this if condition you cannot use apiUrl. because it's let
    }

  }