Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3.1.2章节结尾表达不准确 #103

Open
BlackHole1 opened this issue Aug 12, 2018 · 0 comments
Open

3.1.2章节结尾表达不准确 #103

BlackHole1 opened this issue Aug 12, 2018 · 0 comments

Comments

@BlackHole1
Copy link

在3.1.2的结束部分,你是这么说的:

可以注意到, 在Counter组件中有两处用到CounterStore的getCounterValues函数的地方,第一处是在构造函数中初始化this.state的时候,第二 处是在响应CounterStore状态变化的onChange函数 中,同样一个Store的状态,为了转换为React组件的状态,有两次重复的调用,这看起来似乎不是很好。但是,React组件的状态就是这样,在构造函数中要对this.state初始化,要更新它就要调用this.setState函数。

有没有更简洁的方法?比如说只使用CounterStore.getCounterValues一次?可惜,只要我们想用组件的 状态来驱动组件的渲染,就不可避免要有这两步。那么如果我们不利用组件的状态呢?

这里说到两次的重复调用,以及只使用CounterStore.getCounterValues一次。可以使用下面的代码实现:

constructor(props) {
  super(props);
  // other code
  this.state = {
    count: this.getVal()
  }
}

getVal () {
  return CounterStore.getCounterValues()[this.props.caption]
}

onChange() {
  this.setState({count: this.getVal()});
}

如果你是指单纯的重复代码,那我觉得这句话是不准确的。如果指的是触发Action的次数,那我的疑惑也就明白了。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant