首页 > 解决方案 > componentDidMount 内的函数上没有未使用的表达式

问题描述

如何修复或禁用 ESLint 以忽略

[eslint] Expected an assignment or function call and instead saw an expression. (no-unused-expressions)

在这

authUser
  ? this.setState(() => ({ authUser }))
  : this.setState(() => ({ authUser: null }));

同时,我理解错误的原因并且可以忽略它 - 因为它正在做它打算做的一切。

有没有办法只从这个文档中删除这个错误,而不是全局?或者,我是否有更好的方法来重写它以避免错误同时达到相同的结果?

全组件

const withAuthentication = Component =>
  class WithAuthentication extends React.Component {
    constructor(props) {
      super(props);

      this.state = {
        authUser: null
      };
    }

    componentDidMount() {
      firebase.auth.onAuthStateChanged(authUser => {
        authUser
          ? this.setState(() => ({ authUser }))
          : this.setState(() => ({ authUser: null }));
      });
    }

    render() {
      const { authUser } = this.state;

      return (
        <AuthUserContext.Provider value={authUser}>
          <Component {...this.props} />
        </AuthUserContext.Provider>
      );
    }
  };

export default withAuthentication;

标签: javascriptreactjseslint

解决方案


if then else 试试呢?

firebase.auth.onAuthStateChanged(authUser => {
  if (authUser)
    this.setState(() => ({ authUser })) 
  else
    this.setState(() => ({ authUser: null })); 
});

推荐阅读