【问题标题】:React : Expected an assignment or function call and instead saw an expressionReact :期望一个赋值或函数调用,而是看到一个表达式
【发布时间】:2019-03-21 14:38:36
【问题描述】:

我是 ReactJS 的新手。我想在用户单击时调用此函数,但同时它给我错误Expected an assignment or function call and instead saw an expression 有人可以帮我解决这个问题吗 谢谢

代码

getSortedData =() => {
    let newSort = 'name asc';
    if (this.state.sorteData === newSort) 'name desc';

    this.setState({sortedData: newSort}, () => {
        this.getData();
    })
}

【问题讨论】:

  • 您忘记分配给变量。 if (this.state.sorteData === newSort) newSort = 'name desc';
  • 其实我想切换顺序。如果用户第一次点击我想用名称更新它 asc ,如果用户第二次点击我想用名称更新 desc
  • 此错误消息来自 linter,对吗?不是语法错误,代码有效。

标签: javascript reactjs


【解决方案1】:

认为你的问题是这一行 if (this.state.sorteData === newSort) 'name desc'; 有一个任意字符串。

如果您打算将其分配给新排序,请尝试将其添加到:

if (this.state.sorteData === newSort) {
 newSort = 'name desc';
}

【讨论】:

  • 其实我想切换顺序。如果用户第一次点击我想用 name asc 更新它,如果用户第二次点击我想用name desc更新它
【解决方案2】:

这与其他答案基本相同,但希望能帮助您了解:

let newSort = (this.state.sorteData === newSort) ? 'name desc' : 'name asc';

【讨论】:

    【解决方案3】:

    如果你想切换顺序试试这个方法。

    getSortedData = () => {
        this.setState((prevState, props) => ({
            sortedAscending: !prevState.sortedAscending
        }), () => {
            this.getData();
        });
    }
    
    getData = () => {
      const sorting = this.state.sortedAscending ? 'name asc' : 'name desc'
      // do your stuff
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 2019-10-15
      • 2021-04-12
      • 2022-01-14
      • 2017-09-09
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多