有没有更好的方法来写这个?就像setState(ContentStore.getAll())
会做同样的事情吗?我认为这看起来不必要地混乱,无论如何,精简代码以提高可读性是很重要的!
class Element extends Component {
...
setContentState = () => {
const {
basename,
bookmark,
contents,
} = ContentStore.getAll();
this.setState({
basename,
bookmark,
contents,
});
...
}
}
答案 0 :(得分:1)
有这样一个方便的功能:
const obj = {
basename: 1,
bookmark: 2,
contents: 3,
aaa: 4
}
const pick = (obj, keys) =>
Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })))
const picked = pick(obj, ['basename', 'bookmark', 'contents'])
console.log(picked)
现在您可以:
const pick = (obj, keys) =>
Object.assign({}, ...keys.map(key => ({ [key]: obj[key] })))
class Element extends Component {
...
setContentState = () => {
const data = ContentStore.getAll();
const result = pick(data, ['basename', 'bookmark', 'contents'])
this.setState(result);
...
}
}
或者您可以使用Lodash或Underscore中的选择功能。