reactjs - ReactJS - 将状态传递给在构造函数中为空的组件
问题描述
我试图将状态作为道具传递给子组件,当状态传递时,构造函数内的道具和子组件的 componentDidMount 为空。但是在渲染方法中,道具不是空的
我的父组件:项目
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;
解决方案
解决此问题的最简单方法是向 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>
);
}
推荐阅读
- java - 如何从firebase按值获取数据?
- python-3.x - 为什么在构建线性回归模型时会出现值错误?
- excel - VBA 代码导致错误:“没有足够的内存来完成此操作”
- firebase - 调用 Firestore 数据库返回未定义
- c# - .net core 2.1 中的 SAP WS WCF 客户端消耗错误 405
- python - 从模板获取价值到视图
- php - 如何在PHP中对多维数组中的多维数组进行排序
- xml - 什么是 xdmp:值???XQuery、MarkLogic
- spring-boot - 如何在 Thymleaf + springboot 控制器中显示来自 Flux 的数据
- c# - 如何使用信号器以角度读取从 Web api 发送的数据?