在尝试遵循DRY原则时,我开始想知道在反应项目中是否应鼓励以下内容:
const DEFAULT_STATE = {
foo: foobar,
bar: barfoo
}
class Tuna extends Component {
constructor(props) {
super(props)
this.state = DEFAULT_STATE
}
...
reset = () => {
this.setState(DEFAULT_STATE)
}
...
}
还是会更好(假设DEFAULT_STATE内没有嵌套的对象)
const DEFAULT_STATE = {
foo: foobar,
bar: barfoo
}
class Tuna extends Component {
constructor(props) {
super(props)
this.state = {...DEFAULT_STATE}
}
...
reset = () => {
this.setState({...DEFAULT_STATE})
}
...
}
或只是简单地将此(重复代码)
class Tuna extends Component {
constructor(props) {
super(props)
this.state = {
foo: foobar,
bar: barfoo
}
}
...
reset = () => {
this.setState({
foo: foobar,
bar: barfoo
})
}
...
}
谢谢。
答案 0 :(得分:0)
在任何情况下,如果不更改初始对象,都不会有问题。但是如果更改对象,则可能会遇到以下问题,例如:
const DEFAULT_STATE = {
foo: foobar,
bar: barfoo
}
class Tuna extends Component {
constructor(props) {
super(props)
this.state = DEFAULT_STATE
}
...
reset = () => {
this.setState(DEFAULT_STATE)
}
someFunc = () => {
this.state.foo.push({field: 'lol'})
}
someFuncAfterReset = () => {
console.log(this.state.foo) // always [{field: 'lol'}]
}
}
除了第三种情况