all components will have ajax requests, and an error will be reported when switching.
check the cancellation request when uninstalling. I am almost done now. 100 api, must not be written 100 times?
all components will have ajax requests, and an error will be reported when switching.
check the cancellation request when uninstalling. I am almost done now. 100 api, must not be written 100 times?
encapsulate a cancelable api class
1. Encapsulate all requests once according to the http method (get,post,put,delete)
2.
class ApiWithCancel {
get = (url, params) => {
//get, post put, del
return this.makeCancelAble(get(url, params));
}
post = (url, params) => {
return this.makeCancelAble(post(url, params));
}
put = (url, params) => {
return this.makeCancelAble(put(url, params));
}
delete = (url, params) => {
return this.makeCancelAble(fectchDel(url, params));
}
makeCancelAble = (promise) => {
return new Promise(( resolve ) =>
promise.then(val => !this.hasCanceled && resolve(val))
);
}
cancel = () => {
this.hasCanceled = true;
}
}
3. In the constructor of the component used, new an instance of this class
this.api = new ApiWithCancel();
4. When using
const res = await this.api.get(url,params);
5. Cancel when the component is uninstalled
this.api.cancel()
Note: the code may not be used directly because it is encapsulated, but it means that it can be encapsulated into a class, with one new at a time. In addition, putting data in redux can also avoid this kind of alarm, but only if your data or actions are should be placed in redux .
does not use middleware such as redux-thunk or redux-saga? The call to ajax
in the
component is usually triggered only in componentDidmount ()
, but it is also handled by redux.
your situation is that you must have called ajax
in the pure function, which is rejected.
this react official has discussed it in great detail. I'll just give you a code.
if you want to know the whole story, stamp here https://reactjs.org/blog/2015.
.const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
st cancelablePromise = makeCancelable(
new Promise(r => component.setState({...}))
);
cancelablePromise
.promise
.then(() => console.log('resolved'))
.catch((reason) => console.log('isCanceled', reason.isCanceled));
cancelablePromise.cancel(); // Cancel the promise
first of all, this problem is caused by ajax asynchronous callback setState, which occurs when the component is switched, and the component has been destroyed. Then calling setState will warn you.
all of the above methods are effective.
but not all of my current projects use redux to handle asynchrony, because the project situation is basically that an api will be used by a single component.
my solution is to cancel all outstanding requests last time when the route changes, because the problem is caused by the ajax asynchronous callback, so canceling the request will not go through the callback!
in this way, there is no need to introduce redux middleware to handle asynchronism, nor do you have to uninstall each component
1. Write the landing page with react, after calling the background data with axios, judge the route of the page to jump according to the return value, how to jump? 2.axios.get ( login login.action?username= +name+ &password= +pd, {) timeout: 1000...
setting in state: this.state = {checkList: []}; checkList initializes it with an array of the same length as JsonPage: this.setState ({checkList:checkSaveCount}); checkSavaCount is the same length as the following JsonPage. the following creates...
import React from react ; class PublicScreen extends React.Component { constructor(props) { super(props); this.getStyle = this.getStyle.bind(this); } getStyle() { const { width = 1920, height = 1080 } = this.pr...
renderdphtmldvareturnapiBackend: apiBackend ...
react projects cannot save store? using redux, data index.js ReactDOM.render( <Provider store={store}> <Router > < Provider>, document.getElementById( root )) registerServiceWorker() actions export const SET_USER = ...
this method is included in the constructor of most components, so what exactly is this method for constructor(props,context){ super(props,context) } ...
use the Table component of Antd Design, first check out the data, and then select a CheckBox, but when you change pages, that CheckBox will not disappear. For example, when I select the first line on the first page, and then skip to the second page, the ...
I can run before packaging without any error reports. This problem occurs after packaging. reports such an error in the browser, using scaffolding made by create-react-app, and the back end is Node.js, backend. No error is reported: packages two diff...
segmentfault dvaws.open().websocketwebsocketws ws.openfetchGETloginsendfetchCOOKIECOOKIEFETCHCOOKIECOOKIE ...
...
now we need to develop a website to generate front-end pages based on the node ID saved in the database. For example, the json data is: let data=[ {"id":1,"pid":0,"type":"div"}, {"id":2,"pi...
I pass values through redux scenario is when I click on the navigation bar of component 1 and refresh the ajax of component 2 is the data returned by ajax accepted by this.state.contnet what should I write? There is an urgent need for ideas. ...
official example of full copy: this is the official sample code: import { Select } from antd ; const Option = Select.Option; function handleChange(value) { console.log(`selected ${value}`); } ReactDOM.render( <div> <Select defaul...
how to use react to change the value of Input < hr > export default class myForm extends Component{ constructor(props){ super(props); this.state = { id: , }; } change=()=>{ var idIn...
want to set the meta tag to solve the adaptive problem <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"> meta LOGO ...
use list as the option data source for Select, but use callback, which cannot be rendered. Just call it directly, as shown in the figure below. The first method is fine, and the second is not. Because there are many Select, on a page, you need to use th...
< H1 > github address < H1 > error will be reported when using npm run dev const path = require( path ); const merge = require( webpack-merge ); const common = require( . webpack.common.js ); dev-server let BundleAnalyzerPlugin = require( ...
import React from react ; import ReactDOM from react-dom ; import . assets styles index.less ; import Green from . assets images green.png ; import Red from . assets images red.png ; class Circle extends React.Component { constructor...
There are two areas in the State and Lifecycle section that I don t quite understand 1. State Updates are Merged The merging is shallow, so this.setState ({comments}) leaves this.state.posts intact, but completely replaces this.state.comments. ...
like this [array [xxx], array [xxx], array [xxx].] merge all xxx in array into one array [xxx.] ...