我正在尝试将状态作为道具传递给子组件,并且当状态通过时,子组件的构造函数和componentDidMount内部的道具为空。但是在render方法中,道具不是空的
我的父级组件:项目
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;
例如,在此组件中,道具正确渲染,但在构造函数中和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;
答案 0 :(得分:1)
解决此问题的最简单方法是在Project组件中添加一个条件:
{this.state.project &&
this.state.project._id &&
<Tasks projectId={this.state.project._id} />
}
另一种方法是在任务组件中执行此操作:
constructor(props) {
super(props);
this.state = {
projectId: props._id,
tasks: []
};
}
componentDidUpdate(prevProps, prevState, snapshot) {
// compare this.props and prevProps
if (this.props !== prevProps) {
this.setState({
projectId: this.props._id
});
}
}
render() {
return (
<div>
{this.state.projectId}
</div>
);
}