我正在使用包含员工详细信息的Context API传递数组。当我在Employee.js组件中使用该数组并尝试使用map方法呈现每个雇员时,该数组的那些值仅显示在控制台中,而不是使用JSX呈现。
export const employees=[
{
id:1001,
name: "Nafaz Benzema",
salary: 67000,
},
{
id:1002,
name: "Doto Kama",
salary: 23000,
},
{
id:1003,
name: "Chopa Malli",
salary: 14000,
}
];
import React, { Component } from 'react';
import {employees,detailProduct,storeProducts} from './data'
const EmployeeContext=React.createContext();
class EmployeeProvider extends Component {
constructor(props)
{
super(props);
this.state={
employees:employees
}
}
render() {
return (
<EmployeeContext.Provider value={{...this.state}}>
{this.props.children}
</EmployeeContext.Provider>
);
}
}
const EmployeeConsumer=EmployeeContext.Consumer;
export {EmployeeContext,EmployeeProvider,EmployeeConsumer};
import React, {Component } from 'react';
import {EmployeeConsumer} from '../context'
import EmpDisplay from './EmpDisplay';
class Employee extends Component {
render() {
return (
<div>
<EmployeeConsumer>
{
value=>{
value.employees.map(emp=>(
<div className="employees">
{console.log(emp)}// working
<h2>Id : {emp.id}</h2> //not rendering
<h2>Name : {emp.name}</h2> //not rendering
<h2>Salary : {emp.salary}</h2> //not rendering
</div>
));
}
}
</EmployeeConsumer>
</div>
);
}
}
export default Employee;
答案 0 :(得分:0)
您忘了退货:
Employee.js
import React, {Component } from 'react';
import {EmployeeConsumer} from '../context'
import EmpDisplay from './EmpDisplay';
class Employee extends Component {
render() {
return (
<div>
<EmployeeConsumer>
{
value=>{
value.employees.map(emp=>{
return
<div className="employees">
{console.log(emp)}// working
<h2>Id : {emp.id}</h2> //not rendering
<h2>Name : {emp.name}</h2> //not rendering
<h2>Salary : {emp.salary}</h2> //not rendering
</div>
});
}
}
</EmployeeConsumer>
</div>
);
}
}
export default Employee;
答案 1 :(得分:0)
您的示例中有几个“引人入胜”的地方。
<EmployeeContext.Provider value={{...this.state}}>
您确定状态克隆吗?值在每个渲染器上重新计算。 请查看官方文档https://en.reactjs.org/docs/context.html#caveats
最好照原样传递this.state
。
class Employee extends Component { render() {
它看起来像功能组件。
<EmployeeConsumer>{value => { ... }}</EmployeeConsumer>
在您的原始示例中,花括号代表代码块,并返回undefined
并忽略.map
表达式
使用()
来显式声明一个表达式:
<EmployeeConsumer>{value => (...)}</EmployeeConsumer>