React Component Troubleshooting Method

Respond to the NOOB problem that I have:

I have a JSX file that uses Axios to call the API:

fetch-api-data.jsx :

 import * as axios from 'axios'; export class FetchApiData { constructor() { console.log('FetchAPIData loaded'); } shareMyStoryData(URL) { return axios.get(URL) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); }); } } 

I have a component that references an API call:

share-my-story.jsx

 import * as React from 'react'; import * as DOM from 'react-dom'; import PropTypes from 'prop-types'; import './share-my-story.scss'; import FetchApiData from './fetch-api-data'; class ShareMyStory extends React.Component { componentDidMount() { const URL = '/js/feed/sms.json'; const smsData = FetchApiData.shareMyStoryData(URL); console.log('shareMyStory.jsx - componentDidMount: load: ' + URL); } render() { return ( <div className="item"> <h3>{headline}</h3> <h4>{name}</h4> <p>{link}</p> </div> ); } } ShareMyStory.propTypes = { name: PropTypes.string, headline: PropTypes.string, link: PropTypes.string, } DOM.render( <ShareMyStory/>, document.getElementById('share-my-story')); 

However, when webpack compiles the elements and runs in the browser, I get the following error:

TypeError: Cannot read property 'shareMyStoryData' of undefined

Is there a reason why the shareMyStoryData () method is not available in the share-my-story.jsx ? Both files are in the same folder, and I see that both the fetch-api-data.jsx and share-my-story.jsx are collected correctly in my bundle.js file.

+5
source share
2 answers

You have 3 problems in fetch-api-data.jsx :

Pay attention to a fixed example:

 import * as axios from 'axios'; export default class FetchApiData { constructor() { console.log('FetchAPIData loaded'); } static shareMyStoryData(URL) { return axios.get(URL) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.log(error); }); } } 
+1
source

You must export your default class or import it using parentheses.

 const myFunc = () => {...}; export default myFunc; import myFunc from 'myfunc.js'; 

 const myFunc = () => {...}; export myFunc; import { myFunc } from 'myfunc.js'; 
0
source

Source: https://habr.com/ru/post/1271305/


All Articles