我正在获取一些信息并将其置于反应状态。我可以在react状态下记录数据,但是{singleEmployee}
的显示中没有输出...这可能是react v16.8.5中的错误
import React from 'react';
var Airtable = require('airtable');
var base = new Airtable({apiKey: ''}).base('');
class Firm extends React.Component {
constructor(props) {
super(props);
this.state = {
name:props.location.firm.firmName,
year:props.location.firm.yearFounded,
address:props.location.firm.officeAddress,
website:props.location.firm.website,
aum:props.location.firm.aum,
check:props.location.firm.checkSize,
employees:props.location.firm.employees,
focus:props.location.firm.detailedFirmSpecialisations,
loaded:false,
employeesInfo:null,
};
}
componentDidMount(){
const ids = this.state.employees
const employeesInfo = [];
ids.forEach((id)=>{
base('EmploymentHistory').find(id, (err, record)=>{
if (err) {
console.error(err);
return;
}
employeesInfo.push({
name:record.get('Employment ID'),
job:record.get('Job Title'),
investment:record.get('Investment lookup'),
dateStarted: `${record.get('Start Month (1-12)')} ${record.get('Start Year')}`
})
})
})
console.log(employeesInfo)
this.setState({
employeesInfo:employeesInfo,
loaded:false
},()=>
this.setState({
loaded:true
})
)
}
render() {
const {name,year,address,website,aum,check,focus,employeesInfo,loaded} = this.state;
{loaded && console.log(employeesInfo)}
const singleEmployee = employeesInfo && employeesInfo.map(employee=>{
return <h4 key={employee.name}> Name is {employee.name}</h4>
})
if(!loaded){
return(
<div>loading...</div>
)
}
return (
<div>
<h2>{name ? name : 'N/A'} Audit Report</h2>
<h4>Year Founded {year ? year : 'N/A'}</h4>
<h4>Address {address ? address : 'N/A'}</h4>
<h4>Website {website ? website : 'N/A'}</h4>
<h4>AUM {aum ? aum : 'N/A'}</h4>
<h4>Cheque Size {check ? check : 'N/A'}</h4>
<h4>Investment Focus {focus ? focus : 'N/A'}</h4>
<h2>Employees</h2>
{singleEmployee}
</div>
);
}
}
答案 0 :(得分:0)
由于employeesInfo
是一个数组,因此您需要按索引来获取一个项目,例如
const singleEmployee = employeesInfo && (<h4 key={employeesInfo[0].name}> Name is {employeesInfo[0].name}</h4>)
您在此处的代码:
const singleEmployee = employeesInfo && employeesInfo.map(employee=>{
return <h4 key={employee.name}> Name is {employee.name}</h4>
})
将在singleEmployee
中存储反应元素数组,而不是单个项目
您似乎应该先在employeesInfo
中找到元素,但是您没有ID。
我为您提供了一个简单的版本,您尝试实现的目标是: https://jsfiddle.net/9L8u7fex/
答案 1 :(得分:0)
我认为用于呈现employeeInfo的代码没有任何问题。您在这里遇到的问题是有关将更多值推入异步运行的数组的方式。我建议您将列表保存为状态。
您可以在沙箱https://codesandbox.io/s/0v3xo8p4yp上参考我的示例。如果您注释掉setTemp,则实际上仅在更新列表后才触发新的渲染。如果您将此代码注释掉,新列表将永远不会出现在dom中。我认为这与您的问题非常相似