简体   繁体   English

ReactJS-更改单独的类属性时更新组件

[英]ReactJS - updating components when separate class property is changed

In my project I have an html doc with some react code, for instance: 在我的项目中,我有一个带有一些反应代码的html文档,例如:

var Test = React.createClass({
  getInitialState: function() {
    return {storage: this.props.storage};
  },
  render: function() {
    return (
      <h2>
        {this.state.storage}
      </h2>
    );
  }
});

In another class, AppMan, I have a property called storageLeft . 在另一个类AppMan中,我有一个名为storageLeft的属性。 If I render the Test component like: 如果我将Test组件渲染为:

<Test storage={AppMan.storageLeft}/>

What is the correct way to go about updating the Test component whenever storageLeft is changed inside the AppMan class? 每当在AppMan类中更改storageLeft时,更新Test组件的正确方法是什么? I'm not sure if passing it as a property of the component is the right way to go about it. 我不确定将其作为组件的属性传递是否正确。 Initially, all I can think of is doing a setInterval and constantly doing this.setState({storage: AppMan.storageLeft}); 最初,我能想到的就是执行setInterval并不断执行this.setState({storage: AppMan.storageLeft}); or something along those lines. 或类似的规定。 Any better ideas? 还有更好的主意吗?

Setting state via props is an anti-pattern . 通过道具设置状态反模式 You should save storageLeft in the AppMan component's state and then pass that state to the Test component as a prop. 您应该将storageLeft保存为AppMan组件的状态,然后将该状态作为道具传递给Test组件。 A component automatically re-renders itself and its children (if needed) when you change its state. 更改状态后,组件会自动重新渲染其自身及其子级(如果需要)。

The docs state that: 文档指出:

To implement interactions, we introduce mutable state to the component. 为了实现交互,我们向组件引入了可变状态。 this.state is private to the component and can be changed by calling this.setState(). this.state对组件是私有的,可以通过调用this.setState()进行更改。 When the state updates, the component re-renders itself. 状态更新时,组件会重新渲染自己。

This way your components stay in sync when you pass state as a prop. 这样,当您传递状态作为道具时,您的组件将保持同步。

AppMan.js AppMan.js

<Test storage={this.state.storageLeft} />

Test.js Test.js

var Test = React.createClass({
  render: function() {
    return (
      <h2>
        {this.props.storage}
      </h2>
    );
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM