对象属性的有效setState?

时间:2018-09-10 00:50:13

标签: javascript reactjs ecmascript-6

有没有更好的方法来写这个?就像setState(ContentStore.getAll())会做同样的事情吗?我认为这看起来不必要地混乱,无论如何,精简代码以提高可读性是很重要的!

class Element extends Component {
 ...
   setContentState = () => {
     const {
      basename,
      bookmark,
      contents,
   } = ContentStore.getAll();

   this.setState({
     basename,
     bookmark,
     contents,
   });
 ...
}

}

1 个答案:

答案 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);
    ...
  }
}

或者您可以使用LodashUnderscore中的选择功能。