I use setState
with a callback to ensure that everything will be launched after the status update.
...
this.setState({enabled : true},this.getData);
}
getData () {
const self = this;
fetch(this.props.url,{
method : 'post',
body : this.state
}).then(function (response) {
return response.json();
}).then(function (result) {
self.update();
});
}
...
setState
called out. this.state.enabled
changes to true
. However, this.getData
not called.
One thing that I found interesting is that this happens for the component that I use through the npm package. In my own code setState
, the callback works as designed.
The specified external component is also packaged by me. I use webpack to create it. Maybe something is wrong with my webpack configuration?
There he is:
const Webpack = require('webpack');
const path = require('path');
module.exports = {
entry: {
index : './src/index.js'
},
output: {
path: path.join(__dirname,'dist'),
filename: '[name].js',
library : 'TextField',
libraryTarget: 'umd'
},
externals : [
{
'react' : {
root : 'React',
commonjs2 : 'react',
commonjs : 'react',
amd : 'react'
}
}
],
module: {
loaders: [
{ test: /\.(js?)$/, exclude: /node_modules/, loader: require.resolve('babel-loader'), query: {cacheDirectory: true, presets: ['es2015', 'react', 'stage-2']} }
]
},
devtool : 'eval'
};
Edit:
, , - , vs, .
setState
, , , :
ReactComponent.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object'
|| typeof partialState === 'function'
|| partialState == null) ?
process.env.NODE_ENV !== 'production' ?
invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.')
: _prodInvariant('85')
: void 0;
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
}
};
ReactBaseClasses.js
setState
, npm, , :
Component.prototype.setState = function (partialState, callback) {
!(typeof partialState === 'object'
|| typeof partialState === 'function'
|| partialState == null) ?
invariant(false, 'setState(...): takes an object of state variables to update or a function which returns an object of state variables.')
: void 0;
this.updater.enqueueSetState(this, partialState, callback, 'setState');
};
react.development.js
. , enqueueSetState
. , enqueueSetState
, :
enqueueSetState: function (publicInstance, partialState) {
if (process.env.NODE_ENV !== 'production') {
ReactInstrumentation.debugTool.onSetState();
process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0;
}
var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState');
if (!internalInstance) {
return;
}
var queue = internalInstance._pendingStateQueue ||
(internalInstance._pendingStateQueue = []);
queue.push(partialState);
enqueueUpdate(internalInstance);
},