【问题标题】:React context value not available in child class component反应上下文值在子类组件中不可用
【发布时间】:2021-01-06 21:50:08
【问题描述】:

我已经在 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>
        )
    }
}

【问题讨论】:

    标签: javascript node.js reactjs context-api react-class-based-component


    【解决方案1】:

    你可以使用 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)

    【讨论】:

      【解决方案2】:

      正如你所说你是新来的反应,你仍然工作得那么好。这个错误可能是你没有在你的员工组件中导入上下文(employeeContext),如果你已经导入,那么我建议你使用转换它进入功能组件并使用(useContext)钩子会更好,性能和理解明智。 谢谢

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

      【讨论】:

        猜你喜欢
        • 2015-06-22
        • 2020-12-17
        • 1970-01-01
        • 2020-01-01
        • 1970-01-01
        • 2021-02-03
        • 2021-08-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多