如何使用ES6将状态保存在React组件中 [英] How can i keep state in a React component using ES6

查看:87
本文介绍了如何使用ES6将状态保存在React组件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在ES6中使用有状态的React组件,但是当我定义构造函数时,构造函数只会在组件被多次渲染时(从其父级)被调用一次。示例如下所示。

I'm trying to use a stateful React component with ES6 but when I define a constructor the constructor will only be called once while the component is rendered multiple times (from its parent). Example shown below.

class SubComponent extends React.Component {
  constructor(props) {
    super(props);
    console.log("Creating sub component");
    this.state = { count: props.count };
  }

  render() {
    console.log("Rendering sub component", this.state.count);
    return (<div>count: {this.state.count}</div>);
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    console.log("Creating app");
    this.state = { count: 0 };
    this.tick = this.tick.bind(this);
    setInterval(this.tick, 1000);
  }

  tick() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    console.log("Rendering app", this.state.count);
    return (<SubComponent count={this.state.count} />);
  }
}

这不会更新渲染输出(它将始终是 count:0 )但日志将输出:

This will not update the rendered output (it will always be count: 0) but the logs will output:

Creating app
Rendering app 0
Creating sub component
Rendering sub component 0
Rendering app 1
Rendering sub component 0
Rendering app 2
Rendering sub component 0
Rendering app 3
Rendering sub component 0
...

这是一个JSFiddle: http://jsfiddle.net/jor0xu1a/1/

Here's a JSFiddle: http://jsfiddle.net/jor0xu1a/1/

我知道示例 SubComponent 不需要状态,但我尝试使其尽可能简单地显示我的问题。

I'm aware that the example SubComponent doesn't need a state but I tried making it as simple as possible to show my problem.

我缺少什么?

推荐答案

我推荐阅读 getInitialState中的道具是一个反模式

基本上,尽可能少的组件应具有状态。正如其他答案已经说过,在您的情况下,您可以使用 this.props.count 来引用当前值。似乎没有任何理由为什么 SubComponent 应该有自己的状态。

Basically, as few components as possible should have state. As the other answers already said, in your case you can just use this.props.count to refer to the current value. There doesn't seem to be any reason why SubComponent should have its own state.

但是,如果你真的想要从它收到的道具中计算组件的状态,你有责任让它们保持同步,生命周期方法 componentWillReceiveProps

However, if you really want to compute the component's state from the props it receives, it is your responsibility to keep them in sync, with the life cycle method componentWillReceiveProps:

componentWillReceiveProps(nextProps) {
    this.setState({count: nextProps.count});
}

这篇关于如何使用ES6将状态保存在React组件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆