【发布时间】:2019-03-08 03:50:24
【问题描述】:
我正在尝试将状态作为道具传递给子组件,当状态被传递时,构造函数中的道具和子组件的 componentDidMount 为空。但是在 render 方法中,props 不是空的
我的父组件:项目
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import NewTask from '../../../TaskList/NewTask/NewTask';
import Tasks from '../../../TaskList/Tasks/Tasks';
import './Project.css';
class Project extends Component {
constructor(props) {
super(props);
console.log("props received = " + JSON.stringify(props));
this.state = {
project: {}
};
}
componentDidMount() {
const { match: { params } } = this.props;
fetch(`/dashboard/project/${params.id}`)
.then(response => {
return response.json()
}).then(project => {
this.setState({
project: project
})
console.log(project.tasks)
})
}
render() {
return (
<div>
<section className='Project container'>
<NewTask projectId={this.state.project._id} />
<br />
<h4>Coming Soon ...</h4>
<Tasks projectId={this.state.project._id} />
</section>
</div>
);
}
}
export default Project;
例如,在这个组件中,props 被正确渲染,但在构造函数和 componentDidMount() 中是空的。
我的子组件:任务
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import './Tasks.css';
class Tasks extends Component {
constructor(props) {
super(props);
// There are empty
console.log(JSON.stringify(props.projectId));
this.state = {
projectId: props._id,
tasks: []
};
}
componentDidMount() {
// These are empty too ...
console.log(JSON.stringify(this.props));
}
render() {
return (
<div>
// These aren't empty
{this.props.projectId}
</div>
);
}
}
export default Tasks;
【问题讨论】:
-
至少,您可能需要考虑仅在从 fetch 加载项目时有条件地渲染 Task 或类似组件。现在在一段时间内,您正在传递一个未定义的 projectId 属性值,直到 fetch 已解决并且 setState 已执行。此外,如果 fetch 失败,因为没有 catch() 或后备,这至少会有所帮助。
标签: reactjs components state react-props