如何解决组件应该写成eslint-react中的纯函数错误? [英] how to solve Component should be written as a pure function error in eslint-react?

查看:845
本文介绍了如何解决组件应该写成eslint-react中的纯函数错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const Header = React.createClass({
  contextTypes: {
    router: React.PropTypes.object.isRequired,
  },

  render() {
    return (
        <li className={this.context.router.isActive('a') ? 'active' : ''}>
          <Link to="/a/">A</Link>
        </li>
        <li className={this.context.router.isActive('b') ? 'active' : ''}>
          <Link to="/b/">B</Link>
        </li>
    );
  },
});

我使用eslint-config-airbnb检查上面的代码,它显示了一个错误消息,如组件应该写成纯函数。

I use eslint-config-airbnb to check the above code and it show me an error msg like Component should be written as a pure function .

那么如何将上面的组件更改为纯函数?

So how to change the above component to pure function?

谢谢为了你的帮助。

推荐答案

当你有一个哑组件(没有内部状态,生命周期方法等)时,你可以将其写为简单的javascript函数,而不是使用 React.CreateClass 或扩展 React.Component

When you have a "dumb" component (no internal state, lifecycle methods, etc.), you may write it as a simple javascript function as opposed to using React.CreateClass or extending React.Component.

查看文档此处有关纯函数作为组件的一般信息,此处了解 context

Check out the docs here for general information on pure functions as components and here for information specific to context.

所以在你的情况下:

function Header(context) {
  return (
    <li className={context.router.isActive('a') ? 'active' : ''}>
      <Link to="/a/">A</Link>
    </li>
    <li className={context.router.isActive('b') ? 'active' : ''}>
      <Link to="/b/">B</Link>
    </li>
  );
}

Header.contextTypes = {
  router: React.PropTypes.object.isRequired,
}

这篇关于如何解决组件应该写成eslint-react中的纯函数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆