我有以下具有几个组件的react应用。我有两个子组件(卡和模式)和一个父组件(板)。只需单击卡组件中的卡,然后将卡ID发送到板组件即可。电路板组件具有API数据。它使用来自卡组件的卡ID过滤API数据,并以模式组件显示相关数据。
问题是,模态组件甚至在单击卡之前就在开头加载了一个空数组,即projectData。然后,我无法获取数组内的任何元素,并为每个数组调用说“无法获取未定义的属性”。
卡组件:
class TaskItem extends React.Component {
constructor(props) {
super(props);
this.state = {
more_state: false
}
}
render() {
const { sendCardId } = this.props;
return(
<div onClick={() => sendCardId(task.projectID)}>
</div>
)
}
}
主板组件:
class Taskboard extends Component {
constructor(props) {
super(props);
this.state = {
currentID: null,
projectAllData: [],
open: false,
};
}
getPojectId = (projectId) => {
this.setState({
open: true,
currentId: projectId
});
API.get('project/' + projectId)
.then(({ data }) => {
this.setState({
projectAllData: data.response
});
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
}
render(){
return(
<ProjectModal
handleOpen={this.state.open}
handleClosed={this.handleClose}
projectID={this.state.currentId}
projectData={this.state.projectAllData}
/>
<Column
key={key}
index={index}
title={key}
tasks={columns[key]}
getCardId={this.getPojectId}
/>
)
}
}
模式组件:
class ProjectModal extends Component {
constructor(props) {
super(props);
this.state = {
status: 'To do',
};
}
render(){
const { handleOpen, handleClosed, projectData, projectID } = this.props;
return(
<div>{projectData.projectName}</div
)
}
}
答案 0 :(得分:1)
只使用一次setState。
getPojectId = (projectId) => {
API.get('project/' + projectId)
.then(({ data }) => {
this.setState({
projectAllData: data.response,
open: true,
currentId: projectId
});
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
}
并设置初始化状态对象而不是数组
this.state = {
currentID: null,
projectAllData: {projectName: ''},
open: false,
};
或者这可能更好。
this.state = {
currentID: null,
projectAllData: undefined,
open: false,
};
render(){
return(
<>
{
this.state.projectAllData && (
<ProjectModal
handleOpen={this.state.open}
handleClosed={this.handleClose}
projectID={this.state.currentId}
projectData={this.state.projectAllData}
/>
)
}
<Column
key={key}
index={index}
title={key}
tasks={columns[key]}
getCardId={this.getPojectId}
/>
</>
)