【发布时间】:2020-02-20 16:09:46
【问题描述】:
如何将值从 react render 方法传递给 componentDidMount 并使用该值调用 fetch 方法来填充数据。
在下面的代码中,您可能会看到我有两个 fetch 方法,首先 fetch 将数据保存到 'items' 数组和 'items2' 数组应该使用从 render 方法返回的 id 保存一些日期
import React from 'react';
class CustomPage extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
items2: []
};
}
componentDidMount() {
fetch('http://localhost:8000/api/v2/pages/')
.then(response => response.json())
.then(data => this.setState({ items: data }));
fetch('http://localhost:8000/api/v2/pages/' + id) //How to get this id is from the render method
.then(response => response.json())
.then(data => this.setState({ items2: data }));
}
render() {
let id = this.state.items.items.id; //This id I need to pass to the componentDidMount
}
return (
<React.Fragment>
//Here i plan to render the page using the values from the second fetch method
</React.Fragment>
);
}
}
export default CustomPage;
【问题讨论】:
-
你不能打电话给
componentDidMount。相反,请使用您的函数或componentDidUpdate。 -
this.state.items.items.id是如何排在第一位的? -
好的,谢谢@Antonio,所以我应该在 componentDidUpdate 中使用第二个 fetch
-
@NadirLaskar items.id是第一个fetch方法返回的api设置的json值
-
那么你想在第一个 API 调用的响应之后调用第二个 fetch,如果你想在你有 id 后立即调用 fetch
标签: reactjs