reactjs - 在父组件中使用 fetch 传递给子组件
问题描述
在我的 React 应用程序中,我无法fetch
使用父组件的状态获取从父组件调用返回到子组件的数据。
我相信我正在遵循标准做法,但它不起作用。
这是我的父组件的摘录。
class TasksView extends React.Component {
constructor(props) {
super(props);
this.state = {
bus: null
}
this.handleBusLinkClicked = this.handleBusLinkClicked.bind(this);
this.getBusDetailView = this.getBusDetailView.bind(this);
}
{*/ called when a button is clicked /*}
getBusDetailView(bus_pk) {
const response =
fetch("/bus_detail_view/" + bus_pk + "/")
.then(response => response.json())
.then(data => {
this.setState({
bus: data.vehicle
})
}
);
}
render() {
return (
<ChargerBusModal bus={this.state.bus}/>
)
}
这是我的子组件的摘录:
export class ChargerBusModal extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<Modal show={this.props.show} className={"fade fade-scale charger-detail-modal zoomIn"}
id={"bus-detail-modal"}
tabIndex={"-1"}>
<Modal.Header closeButton>
<Modal.Title id={"modal-title"}> Bus Details
</Modal.Title>
</Modal.Header>
<Modal.Body id={"modalBody"}>
<BusDetailContext.Provider value={{
bus: this.props.bus}}>
<Row className={"align-items-center"}>
<Col>
<BusModalInformation/>
</Col>
</Row>
</BusDetailContext.Provider>
</Modal.Body>
<Modal.Footer>
<Button variant={"secondary"} dataDismiss={"modal"} onClick={this.props.onHide}>Close</Button>
<Button variant={"primary"}> Save Changes </Button>
</Modal.Footer>
</Modal>
)
}
}
}
问题是,在子组件中getBusDetailView(bus_pk)
调用和this.state.bus
设置this.props.bus
的时间始终为空。我希望它是父组件的值this.state.bus
,但事实并非如此。我确认data.vehicle
不为空。
你知道发生了什么吗?
解决方案
this.props.state.bus
- 你试过这个吗?
我知道这已经一年多了;但是,当我发现这个问题时,我是一个初学者并且遇到了类似的问题(将状态从父组件传递到子组件)。就我而言,在子组件上我必须使用this.props.state
& 然后是父状态中的相关对象或元素。
版主:请酌情修改或删除。
推荐阅读
- objective-c - WKWebView 未在 NSWindow 中加载 URL
- saucelabs - Saucelabs 会话未正确关闭
- reactjs - React componentDidMount 在渲染之前执行
- sql - 寻找在 Azure 分析服务中实现角色扮演维度(表格)
- javascript - 我知道为什么我会得到意外的 { 令牌,但是当我的 php 需要将数据集合发送到 javascript 时,我不知道如何解决它
- c# - 从空项目创建 ASP.NET Core 3 MVC
- java - 将 ByteBuffer 转换为字符串删除位于字符串末尾的字符串换行符?
- c# - 从 url 位置下载 PDF 文件会生成 HTML 文件
- ios - 弱到强引用仍然在查找时崩溃
- ios - 如何在 Flutter 中对齐 SingleScrollView 中的组件?