![](/img/trans.png)
[英]Can we pass props from Parent to Child component in React, and set the props as state of child component?
[英]React - can't set component's state from props
反应很新,我面临着意外的行为。
我正在尝试使用我的react应用程序可视化来自数据库的数据(数据可视化的ChartJS)
这是我的App.js(我从create-react-app
),在其中我从服务器的端点作为JSON文件获取数据,并将其传递给BarGraph组件:
class App extends Component {
constructor() {
super();
this.state = {
records_lst : [],
}
}
componentWillMount() {
this.fetchData();
}
fetchData() {
let data = fetch('http://127.0.0.1:5000/api/dbrecords')
.then((resp) => {
resp.json().then((res) => {
this.setState({
records_lst : res,
});
});
})
}
render() {
return (<div className="App">
<BarGraph
label1={'Toolbox - whole'}
label2={'tu-ma'}
textTitle={'Just a Test'}
times={this.state.records_lst.length}
/>
</div>);
}
}
状态records_lst仅保存一个json数组,每个json是数据库的一行。
现在,我想做的是通过计算records_lst
数组的长度来计算数据库中有多少行,并将其发送到BarGraph组件(如下所示)以显示具有该值的单个条形,但是出于某种原因,我不能!
这是条形图:
class BarGraph extends Component {
constructor(props) {
super(props);
this.state = {
chartData : {
labels: [this.props.label1],
datasets: [
{
label: [this.props.label2],
data: [this.props.times]
}
]
}
}
}
我注意到的是,组件的属性正确,因此可以正确计算“时间”,但是组件的状态没有选择该数字。 Chrome的devtool的屏幕截图,为了清晰起见
最后,如果在App.js中,当我使用所有道具调用时,我将把times={44}
(或任何其他数字)显示为正常。 我猜出于相同的原因, label : [this.props.label2]
可以工作。
我在这里想念什么?
谢谢!
采用
data: [props.times]
代替
data: [this.props.times]
并且constructor
将仅被调用一次,并且是在您第一次加载组件时,因为到那时您可能将没有必要的props
,因为您是异步获取它的。 这样更好地使用它。
componentwillReciveprops(props){
this.setState({data:props.times})
}
@mayak在上面正确说过......构造函数只被调用一次
afaik,不要在构造函数中将您的道具置入您的状态。
在render方法中轮询这些道具。
class BarGraph extends Component {
constructor(props) {
super(props);
}
render() {
var data = {
chartData : {
labels: [this.props.label1],
datasets: [
{
label: [this.props.label2],
data: [this.props.times]
}
]
}
return (
<div>hello</div>
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.