【问题标题】:Unexpected token, expected ";"意外的令牌,应为“;”
【发布时间】:2020-10-23 12:41:22
【问题描述】:

有人可以帮我为什么我得到 ==> Unexpected token, expected ";" 的错误

const AppRoot = () => {
  const [tabIndex, setTabIndex] = React.useState(1);
  const handleTabsChange = index => {
    setTabIndex(index);
  };
  this.state={
    backgroundColor: 'black',
    backgroundColor2: 'black',
    pressed: false,
  };
  changeColor(){
    if(!this.state.pressed){
       this.setState({ pressed: true,backgroundColor: 'red', backgroundColor2: 'black'});
    } else {
      this.setState({ pressed: false, backgroundColor: 'black' ,backgroundColor2: 'red'});
    }
  }

【问题讨论】:

  • 你也错过了结束}但这可能只是一个复制粘贴错误
  • 从您的代码中我可以看到... AppRoot 没有关闭? ...除此之外,您为什么要使用 useState 和 this.state ?我不是 sur 但如果你的组件没有扩展 React.class 你将无法使用 this.state !
  • 你在功能组件中使用这个.....
  • 请翻阅文档,检查功能组件和类组件的区别。也有很多关于这个的帖子:When to use ES6 class based React components vs. functional ES6 React components?
  • 长话短说,你正在使用函数组件,当你将它与 Hooks 一起使用时,你不应该使用 .SetState(),而是使用一个 set 函数,你会在其中得到来自 @ 的响应987654325@ 钩子(在您的示例中,您应该使用setTabIndex())。

标签: javascript react-native


【解决方案1】:

changeColor 需要标记为函数function changeColor() {}
或变量const changeColor = () => {}

【讨论】:

    【解决方案2】:
    1. 由于您使用的是 react 钩子,因此您应该对所有状态使用 React.useState。 (最佳做法)

    因此,您应该使用 React.useState 而不是 this.state={...},例如

    const [backgroundColor, setBckgroundColor] = React.useState('black')
    const [backgroundColor2, setBckgroundColor2] = React.useState('black')
    const [pressed, setPressed] = React.useState(false)
    

    const [myState, setMyState] = React.useState({
        backgroundColor: 'black',
        backgroundColor2: 'black',
        pressed: false,
    })
    
    
    1. 您应该使用箭头函数。
    const changeColor = () => {
        if(!this.state.pressed){
           this.setState({ pressed: true,backgroundColor: 'red', backgroundColor2: 'black'});
        } else {
          this.setState({ pressed: false, backgroundColor: 'black' ,backgroundColor2: 'red'});
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 1970-01-01
      • 2019-09-16
      • 2016-12-28
      • 1970-01-01
      • 2017-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多