【问题标题】:React EsLint - Component should be written as pure function and after changed it to pure function can't read the property anymoreReact EsLint - 组件应编写为纯函数,将其更改为纯函数后无法再读取属性
【发布时间】:2018-05-24 14:28:50
【问题描述】:

所以我有这个简单的类,然后按照 eslint 告诉我的方法将其更改为纯函数

 class user extends Component {
          render(){
            return(
              <Aux>
        <UserTable title="User" type="user" role={this.props.location.roleAction}/>
              </Aux>
            )
          }
        }
    export default user;

然后我得到了 eslint 错误,说组件应该写成纯函数,我尝试将其更改为如下所示的纯函数

    const user = () => (
      <Aux>
        <UserTable title="User" type="user" role={this.props.location.roleAction} />
      </Aux>
    );  

export default user;

将其更改为箭头函数后,我无法读取 this.props.location.roleAction 我收到错误“无法读取未定义的属性“位置””。为什么会这样发生?修复错误的任何解决方案,以便我可以使用箭头功能并能够读取属性。当我使用以前的书面组件时,它工作正常。

任何帮助将不胜感激。

【问题讨论】:

  • this 关键字仅对引用它自己的类有效。然后,看看下面的答案。

标签: javascript reactjs


【解决方案1】:

在纯函数(“无状态功能组件”或 SFC)形式中,您会收到 props 作为参数:

const user = props => ( // <−−−− Here
  <Aux>
    <UserTable title="User" type="user" role={props.location.roleAction} />
                                              ^−−−−−− no `this` here since it's
                                                      a parameter
  </Aux>
);

这在文档here 中有介绍。这是一个简单的可运行示例:

const Example = props => (
  <div>{props.text}</div>
);

ReactDOM.render(
  <div>
    <Example text="one" />
    <Example text="two" />
  </div>,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 2020-10-30
    • 2021-08-08
    • 1970-01-01
    • 2016-10-02
    • 2016-06-20
    • 2017-07-14
    • 2017-05-12
    • 1970-01-01
    相关资源
    最近更新 更多