В документации React рекомендуется использовать componentDidMount
для вызовов API.
Также, когда вы извлекаете данные, вы должны сохранять их в состоянии.Позже данные будут доступны в методе рендеринга.
Вот как вы должны настроить свой код :
constructor(props) {
super(props);
this.state = { imageslink: null }
}
componentDidMount() {
axios.get('reactjs.json').then( res => {
this.setState({ imageslink: res.data })
})
}
render() {
const { imageslink } = this.state
if (imageslink) {
// Here you can access this.state.imageslink,
// because they will be fetched.
}
}
Вот общий AxiosПриведите пример:
class App extends React.Component {
constructor(props) {
super(props)
this.state = { users: [] }
}
componentDidMount() {
axios.get('https://reqres.in/api/users?page=1')
.then(response => this.setState({ users: response.data.data }))
}
renderUsers() {
const { users } = this.state
return users.map( user => (
<div key={user.id}>{user.first_name} {user.last_name}</div>
))
}
render() {
return <div>{ this.renderUsers() }</div>
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>