class Example extends React.Component {
state = { data: [] };
controller = new AbortController();
componentDidMount() {
fetch('/url', {
signal: this.controller.signal,
})
.then(res => res.json())
.then(data => this.setState({ data }));
}
componentWillUnmount() {
this.controller.abort();
}
render(){
return ( /* ... */ );
}
}
Так вот, будут ли ПРОСТЫЕ примеры реализации токен авторизации между этими двумя фреймворками?
import React from 'react';
import Cookie from 'js-cookie';
class SimpleExample extends React.Component {
state = {
isProcessing: false,
token: Cookie.get('token'),
data: null,
};
handleSignIn = () => {
this.setState({ isProcessing: true });
fetch('/singin', {
method: 'POST',
data: JSON.stringify({ login: 'admin', pass: 'zx23ww' }),
})
.then(res => res.json())
.then(data => {
this.setState({
isProcessing: false,
token: data.token,
});
Cookie.set('token', token);
});
};
handleLogout = () => {
Cookie.erase('token');
this.setState({ token: null });
};
handleGetProtectedData = () => {
fetch('/protected'{
method: 'GET',
headers: {
Authorization: `Bearer ${this.state.token}`,
},
})
.then(res => res.json())
.then(data => {
this.setState({ data });
});
};
render() {
const { isProcessing, token } = this.state;
if (isProcessing) return <div>...initialization</div>;
const isSignedIn = !!token;
return isSignedIn ? (
<div>
<h1>You're signed in</h1>
<button onClick={this.handleLogout}>Logout</button>
<button onClick={this.handleGetProtectedData}>Get protected data</button>
</div>
) : (
<div>
<h1>You're not signed in</h1>
<button onClick={this.handleSignIn}>Sign in</button>
</div>
);
}
}
<Link to={`/tasks/${item.id}`}>Open</Link>
<Route exact path="tasks/:id" component={TaskDetails} />
import React from 'react';
import tasks from '../data/tasks';
const TaskDetails = ({ match }) => {
const { id } = match.params;
const task = tasks.find(item => item.id === id);
return ( /* ... */ );
}
export default TaskDetails;
export default selector => document.querySelector(selector);
import React, { Component } from 'react';
import $ from './param';
import './style.css';
// ...
const Example = () => {
const [isActive, setIsActive] = useState(false);
const handleClick = () => {
setIsActive(!isActive);
};
return (
<div>
<div className={isActive ? 'active' : ''}>Example</div>
<button onClick={handleClick}>Toggle active</button>
</div>
);
};
<Script src={src} onLoad={onLoad} />
import React from 'react';
class Script extends React.Component {
static displayName = 'Script';
static scriptObservers = {};
static loadedScripts = {};
static erroredScripts = {};
static idCount = 0;
scriptLoaderId = `id${this.constructor['idCount']++}`;
componentDidMount() {
const { onError, onLoad, src } = this.props;
if (this.constructor.loadedScripts[src]) {
if (onLoad) onLoad();
return;
}
if (this.constructor.erroredScripts[src]) {
if (onError) onError();
return;
}
if (this.constructor.scriptObservers[src]) {
this.constructor.scriptObservers[src][this.scriptLoaderId] = this.props;
return;
}
this.constructor.scriptObservers[src] = { [this.scriptLoaderId]: this.props };
this.createScript();
}
createScript() {
const { onCreate, src, attributes } = this.props;
const script = document.createElement('script');
if (onCreate) {
onCreate();
}
if (attributes) {
Object.keys(attributes).forEach(prop => script.setAttribute(prop, attributes[prop]));
}
script.src = src;
if (!script.hasAttribute('async')) {
script.async = true;
}
const callObserverFuncAndRemoveObserver = (shouldRemoveObserver) => {
const observers = this.constructor.scriptObservers[src];
Object.keys(observers).forEach((key) => {
if (shouldRemoveObserver(observers[key])) {
delete observers[this.scriptLoaderId];
}
});
};
script.onload = () => {
this.constructor.loadedScripts[src] = true;
callObserverFuncAndRemoveObserver((observer) => {
if (observer.onLoad) observer.onLoad();
return true;
});
};
script.onerror = () => {
this.constructor.erroredScripts[src] = true;
callObserverFuncAndRemoveObserver((observer) => {
if (observer.onError) observer.onError();
return true;
});
};
document.body.appendChild(script);
}
componentWillUnmount() {
const { src } = this.props;
const observers = this.constructor.scriptObservers[src];
if (observers) {
delete observers[this.scriptLoaderId];
}
}
render() {
return null;
}
}
export default Script;
const { header: Header, footer: Footer } = this.props;
return (
<Fragment>
<Header />
<Footer />
</Fragment>
);
<DropDown onClickHandler={yourHandler} data={yourData} />
class Dropdown extends React.component {
render() {
const { data, onClickHandler } = this.props;
return (
<ul>
{data.map((number, i) =>
<li key={i} onClick={onClickHandler}>{number}</li>
)}
</ul>
)}
}
handleSearchChange = (e, { value }) => {
this.setState({ filter: value });
};
const results = data.filter(item => item.title.toLowerCase().includes(filter.toLowerCase()));
TransitionGroup is a state machine for managing the mounting and unmounting of components over time.
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script>
function Greetings(props) {
return React.createElement('div', null, 'Hello, World!');
}
</script>
'use strict';
if (process.env.NODE_ENV === 'production') {
module.exports = require('./cjs/react.production.min.js');
} else {
module.exports = require('./cjs/react.development.js');
}
import React from 'react';