我正在尝试从子组件更新父组件状态属性。我正在编写一个小的POC,它将发送请求以获取一些数据,每次发送请求时都要更新父项state
属性,并让另一个子组件将父项state
属性呈现为图形(使用CanvasJS)。无论如何,我遵循了一些教程,它们似乎在显示相同的内容。但是当我实现它时,出现了Unhandled Rejection (TypeError): this.props.callbackFunction is not a function
错误。这是我的代码:
父母
import React, { Component } from "react";
import H2Request from "./myRequest";
class AllComponents extends Component {
state = {
items: this.props.value
};
callbackFunction = childData => {
this.setState({ items: childData });
};
render() {
return (
<div>
<MyRequest dataFromParent={this.state.items} />
</div>
);
}
}
export default AllComponents;
Child
import React, { Component } from "react";
import axios from "axios";
import "../App.css";
class MyRequest extends Component {
handleClick = () => {
axios.get("http://localhost:8003").then(response => {
this.props.callbackFunction(response.data);
});
};
render() {
return (
<div className="button_container">
<button className="button" onClick={() => this.handleClick()}>
Refresh
</button>
<h1>
Items:
{JSON.stringify(this.props.dataFromParent, null, 2)}
</h1>
</div>
);
}
}
export default MyRequest;
但是当我单击Refresh
按钮时,出现以下错误:
Unhandled Rejection (TypeError): this.props.callbackFunction is not a function
(anonymous function)
src/components/h2Request.jsx:10
7 | axios.get("http://localhost:8003").then(response => {
> 8 | this.props.callbackFunction(response.data);
9 | ^ });
10 | };
我已经尝试在.bind(this)
调用的末尾添加callbackFunction
,但还是一样。
在您的AllComponent中,您已经定义了功能,但未包含在子组件属性中
import React, { Component } from "react";
import H2Request from "./myRequest";
class AllComponents extends Component {
state = {
items: this.props.value
};
callbackFunction = childData => {
this.setState({ items: childData });
};
render() {
return (
<div>
<MyRequest dataFromParent={this.state.items} /> // see no callBackFunction in props
</div>
);
}
}
export default AllComponents;
将您的父组件更改为,(将callbackFunction作为道具添加,因此可以在子组件中以this.props.callbackFunction()
的身份对其进行访问]
import React, { Component } from "react";
import H2Request from "./myRequest";
class AllComponents extends Component {
state = {
items: this.props.value
};
callbackFunction = childData => {
this.setState({ items: childData });
};
render() {
return (
<div>
<MyRequest dataFromParent={this.state.items} callbackFunction={()=>this.callbackFunction()} /> // add callback as props in here
</div>
);
}
}
export default AllComponents;
问题很简单,您没有将道具传递给孩子。
<MyRequest dataFromParent={this.state.items} callbackFunction={this.callbackFunction} />
因此在孩子中,它将可以呼叫this.props.callbackFunction
您必须像这样为Requestcomponent的callbak prop提供一个值
<MyRequest
dataFromParent={this.state.items}
callbackFunction={this.callbackFunction.bind()}
/>
这里是工作codesandbox