如何从get请求(React)获得响应?



我是新的家伙在反应,所以如何把值,我从jsonHandler函数接收到渲染返回语句?

我试了很多次,但总是得到同样的结果。Console.log(jsonData)在jsonHandler函数返回值,我需要,但函数jsonHandler返回承诺和idk如何处理它。用axios也没关系。Get或fetch().

async function jsonHandler () {
let jsonData;
const url = "http://localhost/index.php";
await axios.get(url)
.then(({data}) => {
jsonData = data.data;
});
console.log(jsonData);                        //returns that i need
return jsonData;
}
class Menu extends Component {

...

render() {
console.log(jsonHandler());                       //returns promise
return <div className="MenuWrap">{this.mainHandler(Here Must Be Data From jsonHandler)}</div>;
}
}
export default Menu;

您可以这样做。使用states进行响应式更新。对于setStateAsync函数,我参考了https://stackoverflow.com/a/45744345/13965360,它异步地设置状态值,这意味着它将等待直到API调用完成。如果您使用async而不是thencatch块,则可以将trycatchawait一起使用。

const url = "http://localhost/index.php";
class Menu extends Component {
state = {
jsonData: {},
};
//creating a function that sets the state asynchronously
setStateAsync(state) {
return new Promise((resolve) => {
this.setState(state, resolve);
});
}
//   Fetch the data
async jsonHandler() {
try {
const response = await axios.get(url);
this.setStateAsync({ jsonData: response.data });
console.log(this.state.jsonData); //returns that i need
} catch (error) {
throw new Error(error);
}
}
render() {
return (
<div className="MenuWrap">
{Object.keys(this.state.jsonData).length &&
JSON.stringify(this.state.jsonData)}
</div>
);
}
}
export default Menu;

如果你想在组件呈现后立即调用API,你需要把它放在componentDidMount生命周期中。

Like,async componentDidMount() { await this.jsonHandler(); }

或者,如果您想在单击按钮时调用API,则需要将方法绑定到侦听器,如<button onClick={this.jsonHandler}>.

最新更新