admin管理员组

文章数量:1023204

Function ponents do not support contextType.

I encountered an issue when trying to add context to a React ponent that was wrapped with a React Router withRouter(...) function.

import React, { Component } from 'react'
import UserContext from './UserContext'
class Toolbar extends Component {
  render(){
    return (
      <div>username: this.context.username</div>
    )
  }
}
Toolbar.contextType = UserContext
export default withRouter(Toolbar)

Function ponents do not support contextType.

I encountered an issue when trying to add context to a React ponent that was wrapped with a React Router withRouter(...) function.

import React, { Component } from 'react'
import UserContext from './UserContext'
class Toolbar extends Component {
  render(){
    return (
      <div>username: this.context.username</div>
    )
  }
}
Toolbar.contextType = UserContext
export default withRouter(Toolbar)
Share Improve this question edited Jan 31, 2019 at 21:32 Tom Hofman asked Jan 31, 2019 at 17:48 Tom HofmanTom Hofman 5205 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

The solution to this issue is simply switch the last two lines like so:

export default withRouter(Toolbar)
Toolbar.contextType = UserContext

Function ponents do not support contextType.

I encountered an issue when trying to add context to a React ponent that was wrapped with a React Router withRouter(...) function.

import React, { Component } from 'react'
import UserContext from './UserContext'
class Toolbar extends Component {
  render(){
    return (
      <div>username: this.context.username</div>
    )
  }
}
Toolbar.contextType = UserContext
export default withRouter(Toolbar)

Function ponents do not support contextType.

I encountered an issue when trying to add context to a React ponent that was wrapped with a React Router withRouter(...) function.

import React, { Component } from 'react'
import UserContext from './UserContext'
class Toolbar extends Component {
  render(){
    return (
      <div>username: this.context.username</div>
    )
  }
}
Toolbar.contextType = UserContext
export default withRouter(Toolbar)
Share Improve this question edited Jan 31, 2019 at 21:32 Tom Hofman asked Jan 31, 2019 at 17:48 Tom HofmanTom Hofman 5205 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

The solution to this issue is simply switch the last two lines like so:

export default withRouter(Toolbar)
Toolbar.contextType = UserContext

本文标签: javascriptFunction components do not support contextTypeStack Overflow