this.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response =>
response || fetch(event.request)
).catch(() =>
caches.match('/')
)
);
});
const {createServer} = require('http');
const next = require('next');
const port = parseInt(process.env.PORT, 10) || 4000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({dev});
const handle = app.getRequestHandler();
app.prepare().then(() => {
createServer((req, res) => {
const [, category] = req.url.split(/(?<=^\/products\/+)([^\/]+)/);
if (!category)
handle(req, res);
else
app.render(req, res, '/catalog');
}).listen(port, err => {
if (err)
throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
import React from 'react';
export default class extends React.Component {
static getInitialProps({asPath}) {
const [, category] = asPath.split(/(?<=^\/products\/+)([^\/]+)/);
return {category};
}
render() {
return (
<div>
<h1>Catalog</h1>
<p>{this.props.category}</p>
</div>
);
}
}
<Link href='/catalog' as='/products/some-category'>
<a>Some category</a>
</Link>
<h1>Hello World!</h1>
преобразуется в React.createElement("h1", null, "Hello World!")
class Publication extends React.Component {
state = {
list: []
};
componentDidMount() {
this.timer = setInterval(() => {
this.setState({list: [...this.state.list, new Date().toString()]});
}, 10000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
static childContextTypes = {
list: React.PropTypes.array
};
getChildContext() {
return {
list: this.state.list
};
}
render() {
return (
<div>
<h4>Publication</h4>
{this.props.children}
</div>
);
}
}
const PublicationList = (props, context) => (
<ul>
{context.list.map(e => <li key={e}>{e}</li>)}
</ul>
);
PublicationList.contextTypes = {list: React.PropTypes.array};
для каждого из них создавать свой редьюсер, экшен, константыДостаточно просто
export connect(state => ({list: state.publication.list}))(PublicationList)
class Calc extends React.Component {
state = {
valueA: 0,
valueB: 0
};
handleChange = ({target: {name, value}}) => {
if (name) this.setState({[name]: value});
};
render() {
return (
<div onChange={this.handleChange}>
<input type='text' name='valueA' value={this.state.valueA}/>
<input type='text' name='valueB' value={this.state.valueB} />
</div>
);
}
}
const App = props => (
<div>
<Link to='/'><h1>App</h1></Link>
<Link to='/news'> News </Link>
<Link to='/about'> About </Link>
{props.children}
</div>
);
const Modal = props => (
<div>
<h3>Modal</h3>
<p>{props.data}</p>
<button onClick={props.onClick}>close</button>
</div>
);
const withModal = Component => props => (
<div>
<Component {...props} />
{props.params.id != undefined && <Modal data={props.params.id} onClick={() => {
props.router.goBack();
}}/>}
</div>
);
const News = withModal(props => (
<div>
<h2>News</h2>
<Link to='/news/1'>modal</Link>
{props.children}
</div>
));
const About = withModal(props => (
<div>
<h2>About</h2>
<Link to={{pathname: '/news/1', state: 'about'}}>modal</Link>
{props.children}
</div>
));
const modalStates = {
'about': About
};
ReactDOM.render(
<Router history={browserHistory}>
<Route path='/' component={App}>
<Route path='news' component={News} />
<Route path='about' component={About} />
<Route path='news/:id' getComponent={(nextState, cb) => {
let Component = News;
const {state} = nextState.location;
if (state && state in modalStates) Component = modalStates[state];
cb(null, Component);
}} />
</Route>
</Router>,
document.body
);
componentWillReceiveProps(nextProps) {
if (nextProps.complete && !this.props.complete) this.sendRequest();
}
shouldComponentUpdate(nextProps) {
const changed = Object.keys(nextProps).filter(e => nextProps[e] !== this.props[e]);
if (changed.length == 1 && changed[0] == 'complete') return false;
}
<TestContent name={Test2} />
...
class TestContent extends Component {
render() {
var data={name:"какие-то данные для вывода в выбранном компоненте"};
var Name = this.props.name;
return(
<div>
<Name data={data} />
</div>
)
}
}
const locations = [
{city: "New York"},
{city: "Moscow"}
];
const First = ({city}) => (
<div className="first">
<button data-city={city}>
click
</button>
<p>{city}</p>
</div>
);
const Second = ({city}) => (
<div className="second">
<span>{city}</span>
</div>
);
const list = locations.map((data, i) => <First city={data.city} />);
class TestComponent extends React.Component {
state = {};
handleClick = ({target}) => {
const {city} = target.dataset;
if (city) this.setState({city});
};
render() {
return (
<div onClick={this.handleClick}>
{list}
<Second city={this.state.city} />
</div>
);
}
}
ReactDOM.render(
<TestComponent />,
document.querySelector('[data-role-id="content"]')
);
{
new Date()
.toLocaleTimeString()
.match(/[^:]+|:/g)
.map((e, i) => e == ':' ? <span key={i}>:</span> : e)
}
Component {
state = Object.assign({}, this.props.initialState);
componentDidMount() {
fetch(...).then(data => this.setState(data));
}
...
}
рендер на клиенте:render(<Component />)
getDataFromDB().then(data => response.send(render(<Component initialState={data} />)))
const {get} = require('http');
const {Iconv} = require('iconv');
const {parseString} = require('xml2js');
const {inspect} = require('util');
get('http://www.cbr.ru/scripts/XML_daily.asp', res => {
const data = [];
res
.pipe(new Iconv('cp1251', 'utf8'))
.on('data', chunk => data.push(chunk))
.on('end', () =>
parseString(
Buffer.concat(data),
(err, res) => console.log(inspect(res, {depth: null}))
)
);
});
loader: 'babel-loader',
include: [
path.resolve(__dirname, './src'),
]