You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中使用Context时出现Cannot read properties of undefined (reading 'children')错误求助

React Context 报错:Cannot read properties of undefined (reading 'children') 修复方案

错误根源

  1. WalletProvider 组件参数解构错误
    你的WalletProvider组件错误地将参数写成({props}),React组件的第一个参数就是完整的props对象,此处应直接解构出children属性,而非嵌套的props。原写法中props为undefined,访问props.children自然会抛出错误。

  2. useContext 使用对象错误
    在App组件中,useContext(WalletProvider)是错误用法,useContext需要传入的是createContext创建的上下文对象(即WalletContext),而非Provider组件本身。


修正后的代码

Context 文件(WalletContext.jsx)

import React, { useState, useEffect, createContext } from 'react';
import Web3 from 'web3';

// 设置与value结构一致的默认值,避免解构时出现undefined
const WalletContext = createContext({
  web3Provider: null,
  address: null,
  isConnected: false,
  chainId: '',
  networkId: '',
  errorMsg: '',
  connectWallet: () => {}
})

// 直接解构出children属性
export const WalletProvider = ({ children }) => {
    const [web3Provider, setWeb3Provider] = useState(null)
    const [address, setAddress] = useState(null)
    const [isConnected, setIsConnected] = useState(false)
    const [chainId, setChainId] = useState('')
    const [networkId, setNetworkId] = useState('')
    const [errorMsg, setErrorMsg] = useState('')

    const connectWallet = async () => {
        if (!isConnected) {
          try {
            const web3 = new Web3(window.ethereum)
            setWeb3Provider(web3)
            
            const accounts = await web3.eth.getAccounts()
            setAddress(accounts[0])

            if (accounts.length > 0) {
              const networkId = await web3.eth.net.getId()
              setNetworkId(networkId)
              const chainId = await web3.eth.getChainId()
              setChainId(chainId)
            }
          } catch (error) {
            setErrorMsg(error.message)
          }
          setIsConnected(true)
        }
      } 

    return (
        <WalletContext.Provider value={{
            web3Provider,
            address,
            isConnected,
            chainId,
            networkId,
            errorMsg,
            connectWallet
        }}>
            {children}
        </WalletContext.Provider>
    )
}
export default WalletContext;

App 组件(App.jsx)

import React, { useContext } from 'react'
import WalletContext, { WalletProvider } from '../context/WalletContext'

function App() {
  // 使用WalletContext作为useContext的参数
  const { 
    address, 
    connectWallet
  } = useContext(WalletContext)

  return (
    <WalletProvider>
      <div className="App">
        <button className="button is-primary" onClick={connectWallet}>
          {address && address.length > 0
                    ? `Connected: ${address.substring(0,6)}...${address.substring(38)}`
                    : "Connect Wallet"}       
        </button>
      </div>
    </WalletProvider>
  );
}

export default App;

内容的提问来源于stack exchange,提问作者Fede

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:05:31