如何将一个值从react渲染方法传递给componentDidMount
,并使用该值调用获取方法来填充数据。
[在下面的代码中,您可能会看到我有两种提取方法,首先将数据保存到'items'
数组中,而'items2'
数组应该使用从id
方法返回的render
保存一些日期] >
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;
我如何将值从react渲染方法传递到componentDidMount,并使用该值调用fetch方法来填充数据。在以下代码中,您可能会看到我有两个提取方法,并且...
您不必通过渲染传递id
,您可以在第一个获取响应之后立即调用第二个获取。
确定,您正在componentDidMount中获取API并将某些状态设置为