首页 > 解决方案 > 当我在子组件中提交表单时,如何更新我定义了 contexAPI 的父类的状态?

问题描述

当我从子组件提交表单时,如何更新定义父上下文 api 的类的状态?


import React, {createContext,Component} from 'react'
import http from './services/httpService'
import {MyApiUrl} from './services/httpService'


export const GlobalState = createContext()

export class DataProvider extends Component{

    state={
        jobs:[],
        loadstate:false,
    }

    async populateCategories() {
      
            const {data:jobs}=await http.get(MyApiUrl+'/api/jobs')
            this.setState({jobs})
        
        
console.log('hellow world')
return

}

      

    async componentDidMount(){
        await this.populateCategories()
       
    }


     logPokemon = this.populateCategories.bind(this); 

    // async  setUser() {
       
    //      await this.populateCategories()
    //   }
    

   

render(){
    const {jobs}=this.state;

    const{logPokemon}=this
    const{children}=this.props
    return (
        <GlobalState.Provider value={{logPokemon,jobs}}>
            {children}
        </GlobalState.Provider>
    )
}

  
}

现在来自另一个子组件,当提交表单时,我这样做了,我收到警告:无法对未安装的组件执行 React 状态更新

static contextType = GlobalState

    const {logPokemon} = this.context;
    logPokemon()

标签: reactjsundefinedthisreact-context

解决方案


仅从 React 函数调用 Hooks。类组件不支持钩子 - Hooks-FAQ

你不能在类组件中使用 Hooks,但你绝对可以将类和函数组件与 Hooks 混合在一个树中。组件是使用 Hooks 的类还是函数是该组件的实现细节。从长远来看,我们希望 Hooks 成为人们编写 React 组件的主要方式。

您不能在类基组件中使用createContext钩子或任何其他反应。hooks钩子仅用于功能组件。了解有关挂钩的更多信息


推荐阅读