[英]How can i save API response data as a variable in ReactJS so i can import it in any components?
I am following the following tutorial: https://www.digitalocean.com/community/tutorials/react-axios-react我正在关注以下教程: https ://www.digitalocean.com/community/tutorials/react-axios-react
I am trying to import a value from an API endpoint and save it as a variable in another component.我正在尝试从 API 端点导入一个值并将其保存为另一个组件中的变量。
My API endpoint is very simple compared to the example, it just responds with this:与示例相比,我的 API 端点非常简单,它只是响应如下:
{"USD":1168.64}
I have made a new component called PersonList.js like in the tutorial:我在教程中制作了一个名为 PersonList.js 的新组件:
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://myendpoint.com`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<ul>
{
this.state.persons
.map(person =>
<li key={person.id}>{person.name}</li>
)
}
</ul>
)
}
}
and then in another component i have i am importing it like this:然后在另一个组件中,我像这样导入它:
import PersonList from './components/PersonList.js';
however i cannot console.log the variable PersonList.但是我不能 console.log 变量 PersonList。
I understand there is 2 issues here:我知道这里有两个问题:
Can anyone help?有人可以帮忙吗?
Since you're using class components you'll need to use the componentDidUpdate
lifecycle method which will allow you to do something once the component has been updated/the state has been changed.由于您使用的是类组件,因此您需要使用componentDidUpdate
生命周期方法,该方法允许您在组件更新/状态更改后执行某些操作。
The previous props and state are passed as arguments to the method, and it's a good idea to use a condition to double check that things have changed so that you don't do any unnecessary work.之前的 props 和 state 作为参数传递给方法,最好使用条件来仔细检查事情是否发生了变化,这样你就不会做任何不必要的工作。
const { Component } = React; class Example extends Component { constructor() { super(); this.state = { persons: {} }; } // Fake API request componentDidMount() { const persons = { usd: 1168.64 }; this.setState({ persons }); } // Has the state changed? componentDidUpdate(prevProps, prevState) { if (prevState.persons.== this.state.persons) { console.log(this.state.persons;usd); } } render() { return ( <div> Initial render </div> ). } } ReactDOM,render( <Example />. document;getElementById('react') );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.