我的提供程序组件中的语法错误是什么?

时间:2018-10-23 15:51:21

标签: javascript reactjs

请帮助! https://gyazo.com/c5982a3511467c8ca895ef8ddf708ef1 Syntax error: Unexpected token, expected ; (20:17) 我的组件出现语法错误,不知道为什么  ./src/Provider/index.js 语法错误:意外令牌,预期; (20:17)

18 | }   19 |

  

20 | render(){        | ^     21 |
    22 |返回(     23 |

class index extends React.Component {

constructor() {
    super();
    this.state = {
        books: [],
        currentlyReading:[],
        wantToRead:[],
        read:[],
        addBooks: books => {

    }
}

   render()  {

      return (
         <MyContext.Provider 

        value={{...this.state}}>
      {this.props.children}


       </MyContext.Provider>)
}
}

导出默认索引;

2 个答案:

答案 0 :(得分:1)

 constructor() { // <- 1
    super();
    this.state = { // <- 2
      books: [],
      currentlyReading:[],
      wantToRead:[],
      read:[],
      addBooks: books => { // <- 3

  } // < - 3
 } // < - 2
 // <- 1 ???

您缺少关闭}来关闭构造函数的信息。因此render() { /*..*/ }是语法错误,因为它在方法主体内部而不在类主体中。

答案 1 :(得分:0)

我认为您需要在箭头函数的返回值周围加上括号

  addBooks: books => ({

  })

而且构造函数也缺少}

这是代码的样子

class index extends React.Component {
  constructor() {
    super();
    this.state = {
      books: [],
      currentlyReading:[],
      wantToRead:[],
      read:[],
      // you were missing parenthesis here
      addBooks: books => ({

      })
    }
  // you were also missing this } here
  }

  render()  {

    return (
        <MyContext.Provider 

      value={{...this.state}}>
        {this.props.children}


      </MyContext.Provider>)
  }
}

注意: 您必须将箭头函数的返回值括在括号中的原因是因为它是对象文字。看看documentation