前端react面试题详细解答
指出(组件)生命周期方法的不同
componentWillMount
– 多用于根组件中的应用程序配置
componentDidMount
– 在这可以完成所有没有 DOM 就不能做的所有配置,并开始获取所有你需要的数据;如果需要设置事件监听,也可以在这完成
componentWillReceiveProps
– 这个周期函数作用于特定的 prop 改变导致的 state 转换
shouldComponentUpdate
– 如果你担心组件过度渲染,shouldComponentUpdate
是一个改善性能的地方,因为如果组件接收了新的 prop
, 它可以阻止(组件)重新渲染。shouldComponentUpdate 应该返回一个布尔值来决定组件是否要重新渲染
componentWillUpdate
– 很少使用。它可以用于代替组件的 componentWillReceiveProps
和 shouldComponentUpdate
(但不能访问之前的 props)
componentDidUpdate
– 常用于更新 DOM,响应 prop 或 state 的改变
componentWillUnmount
– 在这你可以取消网络请求,或者移除所有与组件相关的事件监听器
fetch封装
npm install whatwg-fetch --save
npm install es6-promise
export const handleResponse = (response) => {
if (response.status === 403 || response.status === 401) {
const oauthurl = response.headers.get('locationUrl');
if (!_.isEmpty(oauthUrl)) {
window.location.href = oauthurl;
return;
}
}
if (!response.ok) {
return getErrorMessage(response).then(errorMessage => apiError(response.status, errorMessage));
}
if (isJson(response)) {
return response.json();
}
if (isText(response)) {
return response.text();
}
return response.blob();
};
const httpRequest = {
request: ({
method, headers, body, path, query,
}) => {
const options = {
};
let url = path;
if (method) {
options.method = method;
}
if (headers) {
options.headers = {
...options.headers,...headers};
}
if (body) {
options.body = body;
}
if (query) {
const params = Object.keys(query)
.map(k => `${
k}=${
query[k]}`)
.join('&');
url = url.concat