反应上下文值在子类组件中不可用

问题描述

我已经在indexa.js中声明了一个React上下文,并且试图在Employee.js中访问App.js中设置的上下文值。但这并没有赋予我React新的价值。请帮帮我。预先感谢

// index.js

export const employeeContext = React.createContext();
const AppContextInteration = <App></App>
ReactDOM.render(AppContextInteration,document.getElementById('root'));

// App.js

export class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            EmpId: 1,EmpName: 'xxx'
        }
    }

    render() {
        return (
            <div>
                <h1> App Component</h1>
                <p> Employee Id : {this.state.EmpId}</p>
                <employeeContext.Provider value={this.state} >
                     <Employee/>
                </employeeContext.Provider>

            </div>
        )
    }
}
//Employee.js

export class Employee extends React.Component {
    context = employeeContext;
    constructor(props) {
        super(props);
        console.log();
    }
    render() {
        return (
            <div>
                <h1>Employee Component </h1>
                <p> Employee Id  : {this.context.EmpId} </p>
            </div>
        )
    }
}

解决方法

您可以使用Context.Consumer

<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>

https://reactjs.org/docs/context.html

我更喜欢将功能组件与useContext挂钩一起使用(这很容易实现) 您可以参考React hooks tutorial(useContext)

,

正如您所说的,您是新来的人,但是您仍然工作得很好。发生此错误的原因可能是您尚未在员工组件中导入context(employeeContext),如果您已经导入,那么我建议您使用convert将其插入功能组件并使用(useContext)钩子会更好,性能和明智。 谢谢

链接:https://www.youtube.com/watch?v=UjjtvroahBU&list=PLC3y8-rFHvwisvxhZ135pogtX7_Oe3Q3A&index=17&ab_channel=Codevolution