- 如何使这个React / Redux代码干

时间:2017-09-22 21:59:40

标签: javascript reactjs redux

我有重复的代码,我不知道怎么做干(不要重复自己)。

以下两个组件通过dispatch()与React的“自动重新渲染”进行“交谈”。

this.map重复两次。

此模块将在点击时发送操作。

import React from 'react';
import { connect } from 'react-redux';
class Icon extends React.Component {
  constructor(props) {
    super(props);
    this.map = {
      paper: 'bg_paper.jpg',
      light_wood: 'bg_wood.jpg',
      graph: 'bg_graph.jpg'
    };
  }

  flip () {
    this.props.dispatch({type: 'updateIcon', bg_key: $A.nextKey(this.map, this.props.state.bg_key)});
  }

  render () {
    const style = {
      // ... snip
    }

    return (
      <img id = 'bar_icon' onClick={this.flip.bind(this)} style={style} src='_images/sv_favicon.svg'/>
    )

  }
}

const mapStateToProps = state => {
  return {
    state: state.Icon
  }
}

export default connect(mapStateToProps)(Icon);

此组件将自动重新渲染。一切正常。我只想把它弄干。

import React from 'react';
import { connect } from 'react-redux';

// ... snip

class FrameBody extends React.Component {

  constructor(props) {
    super(props);
    this.map = {
      paper: 'bg_paper.jpg',
      light_wood: 'bg_wood.jpg',
      graph: 'bg_graph.jpg'
    };
  }

  render () {

    const style = {
      backgroundImage: 'url(' + '_images/' + this.map[this.props.state.bg_key] + ')'
    };

    return (

      <div id='contents' style={style}>
      </div>

    )
  }
}

const mapStateToProps = state => {
  return {
    state: state.Icon
  }
}

export default connect(mapStateToProps)(FrameBody);

我该怎么办才能有两个this.map实例?

2 个答案:

答案 0 :(得分:1)

您可以将this.map的逻辑提取到类函数中。

getBackgroundImageKey = () => {
  const backgroundMap = {
    paper: 'bg_paper.jpg',
    light_wood: 'bg_wood.jpg',
    graph: 'bg_graph.jpg'
  }
  return backgroundMap[this.props.bg_key]
}

更进一步,添加另一个函数来返回URL并添加字符串插值。

getBackgroundImageURL(){
  const backgroundMap = {
    paper: 'bg_paper.jpg',
    light_wood: 'bg_wood.jpg',
    graph: 'bg_graph.jpg'
  }
  return `url(_images/${backgroundMap[this.props.bg_key]})`;
}

可以让你定义这样的风格

const backgroundImage = this.getBackgroundImageURL()
const style = { backgroundImage };

答案 1 :(得分:0)

好吧,因为你已经在使用Redux并调度动作来翻转,为什么不在那里移动那个逻辑呢?

将当前图片保留在商店中,以便您可以在connect中获取该图片,让您的翻转动作创建者成为拥有该“地图”的thunk,并决定下一张图片是什么。

代替DRYness,您的代码缺乏关注点分离。如果用户点击“翻转”时它只调用道具,那么switch / Icon UI组件将更加可重用和简洁。将此onFlip连接到我提到的动作创建者,您将逻辑放在一个位置,并在另一个位置进行交互。

相关问题