hey guys I have a trouble with fetch functions in my first react js app.
This is the structure of my project:
hello-world
-- app
-- components
-- main.jsx
-- node_modules
-- public
-- build.js
-- index.html
-- package.json
This is what I've installed using npm:
npm install react react-dom babel-core babel-loader babel-preset-es2015 babel-preset-react webpack --save-dev
npm install --save isomorphic-fetch es6-promise
I use webpack webpack.config
module.exports = {
entry: './app/components/main.jsx',
output: {
path: './public/',
filename: "build.js",
},
module: {
loaders: [
{
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
};
package.json
{
"name": "hello-world",
"version": "1.0.0",
"description": "",
"main": "webpack.config.js",
"scripts": {
"build": "webpack -w"
},
"author": "mannuk",
"license": "MIT",
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"react": "^0.14.8",
"react-dom": "^0.14.8",
"webpack": "^1.13.2"
},
"dependencies": {
"es6-promise": "^3.3.1",
"isomorphic-fetch": "^2.2.1"
}
}
This is the file where I build the UI:
main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import 'isomorphic-fetch';
import 'es6-promise';
class Person extends React.Component {
constructor(props){
super(props);
this.state = {people : []};
}
componentWillMount(){
fetch('xxx/people',
method: 'get',
headers: {'token' : 'xxx'}
)
.then((response) => {
return response.json()
})
.then((people) => {
this.setState({ people: people })
})
}
render(){
return <div>
<input type="text" value={this.state.people[0].name}></input>
</div>
}
}
ReactDOM.render(
<Person/>,
document.getElementById('container')
);
If I try to run it through the browser it fails (fetch method is not defined) I have also checked this releated post ES6 `fetch is undefined` and I have included the import with no success. I also included es6-promise import but it fails too.
What am I doing wrong? Is it a config problem or what? When I run 'npm run build' there is no error and the build.js seems to be ok.
It's an exported default, so...
import fetch from 'isomorphic-fetch'
Adding a polyfill for this is the correct approach. Looking at one of my latest projects you just need to do the following imports;
import promise from 'es6-promise';
import 'isomorphic-fetch';
promise.polyfill();
It looks like you've not quite got the es6-promise import correct which requires the .polyfill() method be called. I'd recommend putting these in the entry point of the application as you should only need to import them once.
I'd also recommend you include the babel polyfill;
import 'babel-polyfill';
来源:https://stackoverflow.com/questions/39707954/fetch-method-is-not-defined-using-es6-fetch-in-react