React:需要一个赋值或函数调用,而是看到一个表达式

时间:2019-03-21 14:38:37

标签: javascript reactjs

我是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();
    })
}

3 个答案:

答案 0 :(得分:2)

认为您的问题是此行if (this.state.sorteData === newSort) 'name desc';中存在任意字符串。

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

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

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

如果要切换顺序,请尝试这种方法。

getSortedData = () => {
    this.setState((prevState, props) => ({
        sortedAscending: !prevState.sortedAscending
    }), () => {
        this.getData();
    });
}

getData = () => {
  const sorting = this.state.sortedAscending ? 'name asc' : 'name desc'
  // do your stuff
}