React创建使用上下文Context,遇到Uncaught ReferenceError: Cannot access ‘UserListContext‘ before initialization

Raect开发中使用context,会遇到Uncaught ReferenceError: Cannot access 'UserListContext' before initialization这个问题。

官方文档地址:Context

最初的方案

还原出问题的路径,首先看一下代码路径,一共两个文件在这里插入图片描述

  • UserList.js为父组件
  • CmpUserList.js为子组件

父组件提供数据给子组件。
其次,看一下思路,父组件会创建一个 Context 对象,并导出这个对象,export const UserListContext = React.createContext(),接着子组件使用CmpUserList.contextType = UserListContext来使用上下文。

代码如下:

  • 父组件UserList.js
import React from 'react'
import { connect } from 'react-redux'

import CmpUserList from './CmpUserList'
export const UserListContext = React.createContext()

class UserList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            showPage: 'list',     // 要显示的页面 list:列表
            props
        };
    }
    changePage = (page, props = {}) => {
        this.setState({
            showPage: page,
            props
        })
    }
    render() {
        let showCmp
        if (this.state.showPage === 'list') {
            showCmp = <CmpUserList
                changePage={this.changePage}
                {...this.state.props}
                      />
        }
        return (
            <UserListContext.Provider value={'214'}>
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
                    {showCmp}
                </div>
            </UserListContext.Provider>
        )
    }
}

export default connect((store, props) => {
    return {
        ...props
    }
})(UserList)

  • 子组件CmpUserList.js
import React from 'react'
import { UserListContext } from './UserList'

// 子组件
class CmpUserList extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <div>{this.context}</div>
        )
    }
}

CmpUserList.contextType = UserListContext
export default CmpUserList

然而,报错了。。。
在这里插入图片描述

新方案

解决方案:新建一个js文件创建上下文,并导出给父子组件使用

那么开始吧,

  • 新建一个index.js文件
// 上下文
import React from 'react';
// 用户列表
export const UserListContext = React.createContext()
  • 修改父组件UserList.js
import React from 'react'
import { connect } from 'react-redux'

import CmpUserList from './CmpUserList'
import { UserListContext } from '../../context/index.js'   // 导入这个

export const UserListContext = React.createContext()   // 删除这个


class UserList extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            showPage: 'list',     // 要显示的页面 list:列表/detail:详情/edit:编辑
            props
        };
    }
    changePage = (page, props = {}) => {
        this.setState({
            showPage: page,
            props
        })
    }
    render() {
        let showCmp
        if (this.state.showPage === 'list') {
            showCmp = <CmpUserList
                changePage={this.changePage}
                {...this.state.props}
                      />
        }
        return (
            <UserListContext.Provider value={'214'}>
                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'auto' }}>
                    {showCmp}
                </div>
            </UserListContext.Provider>
        )
    }
}

export default connect((store, props) => {
    return {
        ...props
    }
})(UserList)

  • 修改子组件CmpUserList.js
import React from 'react'
import { UserListContext } from '../../../context'   // 导入这个

import { UserListContext } from './UserList'   // 删掉这个

// 子组件
class CmpUserList extends React.Component {
    constructor(props) {
        super(props)
    }

    render() {
        return (
            <div>{this.context}</div>
        )
    }
}

CmpUserList.contextType = UserListContext
export default CmpUserList

看页面渲染结果,父组件传入的214已经在页面渲染出来了。
在这里插入图片描述

子组件this.context来使用上下文。
在这里插入图片描述
在这里插入图片描述
成功!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值