使用'this.setState'格式避免React.js中的重复函数有什么好的做法?

时间:2016-07-16 22:18:17

标签: reactjs

我有以下代码:

  @autobind
  setName(name){
    this.setState({name: name});
  }

  @autobind
  setLocation(location){
    this.setState({location: location});
  }

  @autobind
  setReference(reference){
    this.setState({reference: reference});
  }

上面放置的所有函数都有类似的结构,我想知道React.js中是否有一个好习惯,以避免重复自己设置不同的状态。

提前致谢。

1 个答案:

答案 0 :(得分:2)

You could make a function that takes the object as a value, rather than the key value and pass it to setState

setValue(object) {
  this.setState(object)
}

and use it like:

<div onClick={() => this.setValue({ reference })} />

but then you may as well just call setState directly.

<div onClick={() => this.setState({ reference })} />

So really you don't need any of those functions because setState is that function.

However, this generalized setValue function could be useful when passing to children.

<Child setParentState={this.setValue} />

and use it

<div onClick={() => this.props.setParentState({ reference })} />

Though I admit I've never done anything like that. Seems to give too much control to child elements, but used sparingly should be fine.